diff --git a/d2ypp2/config/system-stack.env.example b/d2ypp2/config/system-stack.env.example index f35cef7..e43b1ba 100644 --- a/d2ypp2/config/system-stack.env.example +++ b/d2ypp2/config/system-stack.env.example @@ -163,7 +163,8 @@ NEKO_IP_WATCH_INTERVAL=15 NEKO_PLUGINS_ENABLED=true # Redroid Android 13(需要 binderfs 或 /dev/binder*;安装脚本会在支持的内核上自动准备) -ENABLE_REDROID=1 +# 默认关闭以节省推流 CPU;控制台可手动 Start +ENABLE_REDROID=0 REDROID_DEFAULT_PORT=5555 REDROID_PORT_STEP=1 REDROID_INSTANCE_PREFIX=redroid13 @@ -197,30 +198,30 @@ ANDROID_PANEL_VIDEO_BIT_RATE=1024000 DOCKER_OPTIONAL_INSTALL_TIMEOUT=900 # Shared ENABLE_SHELLCRASH=1 -ENABLE_WEBTTY=1 +ENABLE_WEBTTY=0 ENABLE_BROWSER=1 ENABLE_MDNS=1 ENABLE_WIFI_PROFILE=1 -ENABLE_ANDROID_PANEL=1 -# Hub profile defaults +ENABLE_ANDROID_PANEL=0 +# Hub profile defaults(推流机默认关闭非必要模块,控制台可手动 Start) ENABLE_COCKPIT=1 -ENABLE_FILEBROWSER=1 -ENABLE_HOMEPAGE=1 +ENABLE_FILEBROWSER=0 +ENABLE_HOMEPAGE=0 ENABLE_NETDATA=1 -ENABLE_MITMPROXY=1 +ENABLE_MITMPROXY=0 MITMPROXY_WEB_PORT=8086 MITMPROXY_PROXY_PORT=8087 -ENABLE_VSCODE_SERVER=1 +ENABLE_VSCODE_SERVER=0 VSCODE_SERVER_PORT=8440 VSCODE_SERVER_PASSWORD=12345678 -ENABLE_UPTIME_KUMA=1 +ENABLE_UPTIME_KUMA=0 UPTIME_KUMA_PORT=3001 -ENABLE_PULSEAUDIO=1 +ENABLE_PULSEAUDIO=0 PULSEAUDIO_TCP_PORT=4713 ENABLE_KMSCUBE=1 KMSCUBE_AUTOSTART=0 KMSCUBE_DRM_DEVICE=/dev/dri/card0 -ENABLE_OPENCLAW=1 +ENABLE_OPENCLAW=0 OPENCLAW_IMAGE=ghcr.io/openclaw/openclaw:latest OPENCLAW_GATEWAY_PORT=18789 OPENCLAW_BRIDGE_PORT=18790 @@ -229,14 +230,14 @@ OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1 OPENCLAW_CONFIG_DIR=/var/lib/live-openclaw/config OPENCLAW_WORKSPACE_DIR=/var/lib/live-openclaw/workspace -# Studio modules -ENABLE_HOMEASSISTANT=1 -HOMEASSISTANT_AUTOSTART=1 +# Studio modules(默认关闭,控制台可手动 Start) +ENABLE_HOMEASSISTANT=0 +HOMEASSISTANT_AUTOSTART=0 HOMEASSISTANT_IMAGE=ghcr.io/home-assistant/home-assistant:stable HOMEASSISTANT_PORT=8123 HOMEASSISTANT_CONFIG_DIR=/var/lib/live-homeassistant/config -ENABLE_FRIGATE=1 -FRIGATE_USB_AUTOSTART=1 +ENABLE_FRIGATE=0 +FRIGATE_USB_AUTOSTART=0 FRIGATE_USB_SCAN_INTERVAL=60 FRIGATE_IMAGE=ghcr.io/blakeblackshear/frigate:stable FRIGATE_WEB_PORT=5001 @@ -251,7 +252,7 @@ WOL_BROADCAST=255.255.255.255 WOL_PORT=9 WOL_PROBE_INTERVAL=30 WOL_PROBE_CIDR= -ENABLE_NTFY=1 +ENABLE_NTFY=0 NTFY_IMAGE=binwiederhier/ntfy:latest NTFY_PORT=8089 NTFY_CONFIG_DIR=/var/lib/live-ntfy/config @@ -264,5 +265,5 @@ COTURN_MIN_PORT=49160 COTURN_MAX_PORT=49200 COTURN_REALM=live.local COTURN_STATIC_AUTH_SECRET= -# Business profile defaults -ENABLE_SRS=1 +# Business profile defaults(推流不依赖 SRS,默认关闭) +ENABLE_SRS=0 diff --git a/d2ypp2/douyin_youtube_ffplay.py b/d2ypp2/douyin_youtube_ffplay.py index 09b9e1d..4fd6eb4 100644 --- a/d2ypp2/douyin_youtube_ffplay.py +++ b/d2ypp2/douyin_youtube_ffplay.py @@ -436,6 +436,17 @@ def _proxychains_proxy_line(push_proxy: str) -> str | None: return " ".join(parts) +def _is_probable_stream_input(url: str) -> bool: + u = (url or "").strip().lower() + if not u.startswith("http"): + return False + if any(token in u for token in (".flv", ".m3u8", "pull-flv", "pull-hls", "/pull/", "/third/stream-")): + return True + if "live.douyin.com/" in u: + return False + return True + + def _looks_like_youtube_output_rejected(line_lower: str) -> bool: if not any( marker in line_lower @@ -762,6 +773,23 @@ def start_douyin_youtube_ffplay( clean_title = sanitize_title(title) stream_title = sanitize_title(f"{anchor_name}{('_' + clean_title) if clean_title else ''}_{timestamp_str}") print(f"[INFO] {rec_info} 开始推流到 YouTube: {stream_title}") + try: + from src.youtube_relay_log import on_relay_push_start + + ini_text = "" + if os.path.exists(config_file): + with open(config_file, encoding="utf-8-sig") as ini_fp: + ini_text = ini_fp.read() + on_relay_push_start( + process=_live_pm2_name() or "youtube", + anchor_name=anchor_name, + record_url=record_url, + stream_title=stream_title, + real_url=real_url, + youtube_ini_text=ini_text, + ) + except Exception as relay_log_exc: + print(f"[WARN] relay session log start skipped: {relay_log_exc}") # ====================== 视频编码:hardware.env(ARM)→ NVENC → libx264 ====================== _hw_env = _load_simple_env_file(os.path.join(_config_dir, "hardware.env")) @@ -981,9 +1009,13 @@ def start_douyin_youtube_ffplay( _seen_source: set[str] = set() for item in [real_url, *(fallback_urls or [])]: u = (item or "").strip() - if u and u not in _seen_source: - _seen_source.add(u) - source_candidates.append(u) + if not u or u in _seen_source: + continue + if not _is_probable_stream_input(u): + print(f"[WARN] 跳过非直链输入: {u[:120]}") + continue + _seen_source.add(u) + source_candidates.append(u) if not source_candidates: source_candidates = [real_url] source_index = 0 @@ -1245,6 +1277,12 @@ def start_douyin_youtube_ffplay( finally: cleanup_proc(proc) clear_relay_heartbeat(_relay_pm2, base_dir=_script_dir) + try: + from src.youtube_relay_log import on_relay_push_end + + on_relay_push_end(_relay_pm2, anchor_name=anchor_name, reason="push_stopped") + except Exception as relay_log_exc: + print(f"[WARN] relay session log end skipped: {relay_log_exc}") try: recording_time_list.pop(record_name, None) diff --git a/d2ypp2/live-platform/config/defaults/services/android_panel.json b/d2ypp2/live-platform/config/defaults/services/android_panel.json index d5b99e1..9f690cb 100644 --- a/d2ypp2/live-platform/config/defaults/services/android_panel.json +++ b/d2ypp2/live-platform/config/defaults/services/android_panel.json @@ -1,7 +1,7 @@ { "id": "android_panel", "layer": "infra", - "enabled": true, + "enabled": false, "manager": "systemd", "ports": { "http": 5000 }, "env": { diff --git a/d2ypp2/live-platform/config/defaults/services/filebrowser.json b/d2ypp2/live-platform/config/defaults/services/filebrowser.json index 9e615b9..8dce5a0 100644 --- a/d2ypp2/live-platform/config/defaults/services/filebrowser.json +++ b/d2ypp2/live-platform/config/defaults/services/filebrowser.json @@ -1,7 +1,7 @@ { "id": "filebrowser", "layer": "infra", - "enabled": true, + "enabled": false, "manager": "docker", "ports": { "http": 8082 }, "env": { diff --git a/d2ypp2/live-platform/config/defaults/services/frigate.json b/d2ypp2/live-platform/config/defaults/services/frigate.json index cc2f451..360366c 100644 --- a/d2ypp2/live-platform/config/defaults/services/frigate.json +++ b/d2ypp2/live-platform/config/defaults/services/frigate.json @@ -1,11 +1,11 @@ { "id": "frigate", "layer": "studio", - "enabled": true, + "enabled": false, "manager": "docker", "ports": { "http": 5001, "rtsp": 8554, "webrtc": 8555 }, "env": { - "ENABLE_FRIGATE": "1", + "ENABLE_FRIGATE": "0", "FRIGATE_WEB_PORT": "5001", "FRIGATE_CONFIG_DIR": "/var/lib/live-frigate/config", "FRIGATE_MEDIA_DIR": "/var/lib/live-frigate/media" diff --git a/d2ypp2/live-platform/config/defaults/services/homeassistant.json b/d2ypp2/live-platform/config/defaults/services/homeassistant.json index dad4eeb..ba61758 100644 --- a/d2ypp2/live-platform/config/defaults/services/homeassistant.json +++ b/d2ypp2/live-platform/config/defaults/services/homeassistant.json @@ -1,7 +1,7 @@ { "id": "homeassistant", "layer": "studio", - "enabled": true, + "enabled": false, "manager": "docker", "ports": { "http": 8123 }, "env": { diff --git a/d2ypp2/live-platform/config/defaults/services/homepage.json b/d2ypp2/live-platform/config/defaults/services/homepage.json index a3831aa..7a996d3 100644 --- a/d2ypp2/live-platform/config/defaults/services/homepage.json +++ b/d2ypp2/live-platform/config/defaults/services/homepage.json @@ -1,7 +1,7 @@ { "id": "homepage", "layer": "infra", - "enabled": true, + "enabled": false, "manager": "docker", "ports": { "http": 3080 }, "env": { "ENABLE_HOMEPAGE": "1", "HOMEPAGE_PORT": "3080" } diff --git a/d2ypp2/live-platform/config/defaults/services/ntfy.json b/d2ypp2/live-platform/config/defaults/services/ntfy.json index 66ec5af..cf8c2d5 100644 --- a/d2ypp2/live-platform/config/defaults/services/ntfy.json +++ b/d2ypp2/live-platform/config/defaults/services/ntfy.json @@ -1,7 +1,7 @@ { "id": "ntfy", "layer": "studio", - "enabled": true, + "enabled": false, "manager": "docker", "ports": { "http": 8089 }, "env": { diff --git a/d2ypp2/live-platform/config/defaults/services/srs.json b/d2ypp2/live-platform/config/defaults/services/srs.json index d1ff67d..526d6a4 100644 --- a/d2ypp2/live-platform/config/defaults/services/srs.json +++ b/d2ypp2/live-platform/config/defaults/services/srs.json @@ -1,7 +1,7 @@ { "id": "srs", "layer": "infra", - "enabled": true, + "enabled": false, "manager": "docker", "ports": { "http": 8080, diff --git a/d2ypp2/live-platform/config/defaults/services/webtty.json b/d2ypp2/live-platform/config/defaults/services/webtty.json index 3344cb0..b101049 100644 --- a/d2ypp2/live-platform/config/defaults/services/webtty.json +++ b/d2ypp2/live-platform/config/defaults/services/webtty.json @@ -1,7 +1,7 @@ { "id": "webtty", "layer": "core", - "enabled": true, + "enabled": false, "manager": "systemd", "ports": { "http": 7681 }, "env": { diff --git a/d2ypp2/main.py b/d2ypp2/main.py index 1d7d81f..c7706f6 100644 --- a/d2ypp2/main.py +++ b/d2ypp2/main.py @@ -460,6 +460,13 @@ def run_script(command: str) -> None: def clear_record_info(record_name: str, record_url: str) -> None: global monitoring recording.discard(record_name) + recording_time_list.pop(record_name, None) + try: + from src.youtube_relay_slot import release_relay_slot + + release_relay_slot(record_name) + except Exception: + pass if record_url in url_comments and record_url in running_list: running_list.remove(record_url) monitoring -= 1 @@ -1176,11 +1183,25 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None: else: content = f"\r{record_name} 正在直播中..." print(content) - # 检查是否已有直播在录制 - if len(recording) > 0 : - # 如果已有直播在录制,跳过这次录制(主播在线) - # return - continue #如果在循环中 + from src.youtube_relay_slot import ( + claim_relay_slot, + prune_stale_relay_recording, + relay_slot_blocks, + release_relay_slot, + ) + + prune_stale_relay_recording( + recording, + recording_time_list, + pm2=_live_pm2_name() or "youtube", + base_dir=script_path, + ) + if record_name in recording: + recording.discard(record_name) + recording_time_list.pop(record_name, None) + release_relay_slot(record_name) + if relay_slot_blocks(record_name, recording): + continue if live_status_push and not start_pushed: if begin_show_push: diff --git a/d2ypp2/scripts/linux/lib/common.sh b/d2ypp2/scripts/linux/lib/common.sh index 3271cbd..cd04966 100644 --- a/d2ypp2/scripts/linux/lib/common.sh +++ b/d2ypp2/scripts/linux/lib/common.sh @@ -171,18 +171,18 @@ flag_enabled() { } need_docker() { - [ "${ENABLE_SRS:-1}" = "1" ] || \ - [ "${ENABLE_HOMEPAGE:-1}" = "1" ] || \ - [ "${ENABLE_FILEBROWSER:-1}" = "1" ] || \ + [ "${ENABLE_SRS:-0}" = "1" ] || \ + [ "${ENABLE_HOMEPAGE:-0}" = "1" ] || \ + [ "${ENABLE_FILEBROWSER:-0}" = "1" ] || \ [ "${ENABLE_NEKO:-1}" = "1" ] || \ - [ "${ENABLE_REDROID:-1}" = "1" ] || \ - [ "${ENABLE_MITMPROXY:-1}" = "1" ] || \ - [ "${ENABLE_VSCODE_SERVER:-1}" = "1" ] || \ - [ "${ENABLE_UPTIME_KUMA:-1}" = "1" ] || \ - [ "${ENABLE_OPENCLAW:-1}" = "1" ] || \ - [ "${ENABLE_HOMEASSISTANT:-1}" = "1" ] || \ - [ "${ENABLE_FRIGATE:-1}" = "1" ] || \ - [ "${ENABLE_NTFY:-1}" = "1" ] || \ + [ "${ENABLE_REDROID:-0}" = "1" ] || \ + [ "${ENABLE_MITMPROXY:-0}" = "1" ] || \ + [ "${ENABLE_VSCODE_SERVER:-0}" = "1" ] || \ + [ "${ENABLE_UPTIME_KUMA:-0}" = "1" ] || \ + [ "${ENABLE_OPENCLAW:-0}" = "1" ] || \ + [ "${ENABLE_HOMEASSISTANT:-0}" = "1" ] || \ + [ "${ENABLE_FRIGATE:-0}" = "1" ] || \ + [ "${ENABLE_NTFY:-0}" = "1" ] || \ [ "${ENABLE_COTURN:-0}" = "1" ] } @@ -378,7 +378,7 @@ load_env() { NEKO_VIDEO_BITRATE="${NEKO_VIDEO_BITRATE:-1200}" NEKO_BROWSER_RENDER_MODE="${NEKO_BROWSER_RENDER_MODE:-auto}" NEKO_TAMPERMONKEY_REPAIR="${NEKO_TAMPERMONKEY_REPAIR:-1}" - ENABLE_REDROID="${ENABLE_REDROID:-1}" + ENABLE_REDROID="${ENABLE_REDROID:-0}" REDROID_DEFAULT_PORT="${REDROID_DEFAULT_PORT:-5555}" REDROID_INSTANCE_PREFIX="${REDROID_INSTANCE_PREFIX:-redroid13}" REDROID_DATA_PREFIX="${REDROID_DATA_PREFIX:-/var/lib/live-redroid}" @@ -408,20 +408,20 @@ load_env() { REDROID_BOOT_ARGS="${REDROID_BOOT_ARGS} androidboot.redroid_gpu_mode=${REDROID_GPU_MODE}" ;; esac - ENABLE_MITMPROXY="${ENABLE_MITMPROXY:-1}" + ENABLE_MITMPROXY="${ENABLE_MITMPROXY:-0}" MITMPROXY_WEB_PORT="${MITMPROXY_WEB_PORT:-8086}" MITMPROXY_PROXY_PORT="${MITMPROXY_PROXY_PORT:-8087}" - ENABLE_VSCODE_SERVER="${ENABLE_VSCODE_SERVER:-1}" + ENABLE_VSCODE_SERVER="${ENABLE_VSCODE_SERVER:-0}" VSCODE_SERVER_PORT="${VSCODE_SERVER_PORT:-8440}" VSCODE_SERVER_PASSWORD="${VSCODE_SERVER_PASSWORD:-12345678}" - ENABLE_UPTIME_KUMA="${ENABLE_UPTIME_KUMA:-1}" + ENABLE_UPTIME_KUMA="${ENABLE_UPTIME_KUMA:-0}" UPTIME_KUMA_PORT="${UPTIME_KUMA_PORT:-3001}" - ENABLE_PULSEAUDIO="${ENABLE_PULSEAUDIO:-1}" + ENABLE_PULSEAUDIO="${ENABLE_PULSEAUDIO:-0}" PULSEAUDIO_TCP_PORT="${PULSEAUDIO_TCP_PORT:-4713}" ENABLE_KMSCUBE="${ENABLE_KMSCUBE:-1}" KMSCUBE_AUTOSTART="${KMSCUBE_AUTOSTART:-0}" KMSCUBE_DRM_DEVICE="${KMSCUBE_DRM_DEVICE:-/dev/dri/card0}" - ENABLE_OPENCLAW="${ENABLE_OPENCLAW:-1}" + ENABLE_OPENCLAW="${ENABLE_OPENCLAW:-0}" OPENCLAW_IMAGE="${OPENCLAW_IMAGE:-ghcr.io/openclaw/openclaw:latest}" OPENCLAW_GATEWAY_PORT="${OPENCLAW_GATEWAY_PORT:-18789}" OPENCLAW_BRIDGE_PORT="${OPENCLAW_BRIDGE_PORT:-18790}" @@ -429,13 +429,13 @@ load_env() { OPENCLAW_ALLOW_INSECURE_PRIVATE_WS="${OPENCLAW_ALLOW_INSECURE_PRIVATE_WS:-1}" OPENCLAW_CONFIG_DIR="${OPENCLAW_CONFIG_DIR:-/var/lib/live-openclaw/config}" OPENCLAW_WORKSPACE_DIR="${OPENCLAW_WORKSPACE_DIR:-/var/lib/live-openclaw/workspace}" - ENABLE_HOMEASSISTANT="${ENABLE_HOMEASSISTANT:-1}" - HOMEASSISTANT_AUTOSTART="${HOMEASSISTANT_AUTOSTART:-1}" + ENABLE_HOMEASSISTANT="${ENABLE_HOMEASSISTANT:-0}" + HOMEASSISTANT_AUTOSTART="${HOMEASSISTANT_AUTOSTART:-0}" HOMEASSISTANT_IMAGE="${HOMEASSISTANT_IMAGE:-ghcr.io/home-assistant/home-assistant:stable}" HOMEASSISTANT_PORT="${HOMEASSISTANT_PORT:-8123}" HOMEASSISTANT_CONFIG_DIR="${HOMEASSISTANT_CONFIG_DIR:-/var/lib/live-homeassistant/config}" - ENABLE_FRIGATE="${ENABLE_FRIGATE:-1}" - FRIGATE_USB_AUTOSTART="${FRIGATE_USB_AUTOSTART:-1}" + ENABLE_FRIGATE="${ENABLE_FRIGATE:-0}" + FRIGATE_USB_AUTOSTART="${FRIGATE_USB_AUTOSTART:-0}" FRIGATE_USB_SCAN_INTERVAL="${FRIGATE_USB_SCAN_INTERVAL:-60}" FRIGATE_IMAGE="${FRIGATE_IMAGE:-ghcr.io/blakeblackshear/frigate:stable}" FRIGATE_WEB_PORT="${FRIGATE_WEB_PORT:-5001}" @@ -450,11 +450,16 @@ load_env() { WOL_PORT="${WOL_PORT:-9}" WOL_PROBE_INTERVAL="${WOL_PROBE_INTERVAL:-30}" WOL_PROBE_CIDR="${WOL_PROBE_CIDR:-}" - ENABLE_NTFY="${ENABLE_NTFY:-1}" + ENABLE_NTFY="${ENABLE_NTFY:-0}" NTFY_IMAGE="${NTFY_IMAGE:-binwiederhier/ntfy:latest}" NTFY_PORT="${NTFY_PORT:-8089}" NTFY_CONFIG_DIR="${NTFY_CONFIG_DIR:-/var/lib/live-ntfy/config}" NTFY_CACHE_DIR="${NTFY_CACHE_DIR:-/var/lib/live-ntfy/cache}" + ENABLE_WEBTTY="${ENABLE_WEBTTY:-0}" + ENABLE_ANDROID_PANEL="${ENABLE_ANDROID_PANEL:-0}" + ENABLE_FILEBROWSER="${ENABLE_FILEBROWSER:-0}" + ENABLE_HOMEPAGE="${ENABLE_HOMEPAGE:-0}" + ENABLE_SRS="${ENABLE_SRS:-0}" export HOMEASSISTANT_IMAGE HOMEASSISTANT_PORT HOMEASSISTANT_CONFIG_DIR export FRIGATE_IMAGE FRIGATE_WEB_PORT FRIGATE_RTSP_PORT FRIGATE_WEBRTC_PORT FRIGATE_SHM_SIZE FRIGATE_CONFIG_DIR FRIGATE_MEDIA_DIR FRIGATE_PRIVILEGED export NTFY_IMAGE NTFY_PORT NTFY_CONFIG_DIR NTFY_CACHE_DIR @@ -1538,11 +1543,10 @@ detect_preferred_lan_ip() { hostname -I 2>/dev/null | tr ' ' '\n' | grep -E '^[0-9]+\.' | grep -Ev '^(127\.|169\.254\.)' | head -n 1 } -neko_nat1to1_is_usable() { +neko_nat1to1_iface_for_ip() { local candidate="$1" - local iface [ -n "$candidate" ] || return 1 - iface="$(ip -4 addr show 2>/dev/null | awk -v want="$candidate" ' + ip -4 addr show 2>/dev/null | awk -v want="$candidate" ' /^[0-9]+: / { iface=$2 sub(/:$/, "", iface) @@ -1555,7 +1559,23 @@ neko_nat1to1_is_usable() { exit } } - ')" + ' +} + +neko_nat1to1_is_overlay_iface() { + local iface="${1:-}" + case "$iface" in + ""|lo|docker*|br-*|veth*|virbr*|sit*|dummy*) return 1 ;; + tun*|tap*|zt*|tailscale*|wg*|wireguard*) return 0 ;; + *) return 1 ;; + esac +} + +neko_nat1to1_is_usable() { + local candidate="$1" + local iface + [ -n "$candidate" ] || return 1 + iface="$(neko_nat1to1_iface_for_ip "$candidate")" case "$iface" in ""|lo|docker*|br-*|veth*|virbr*|sit*|dummy*) return 1 @@ -1568,6 +1588,33 @@ neko_nat1to1_is_usable() { esac } +resolve_neko_nat1to1() { + local mode="${NEKO_ACCESS_MODE:-lan}" candidate="" lan_ip="" iface="" + lan_ip="$(detect_preferred_lan_ip || true)" + case "$mode" in + remote) + candidate="${NEKO_WIREGUARD_HOST:-}" + if [ -n "$candidate" ] && neko_nat1to1_is_usable "$candidate"; then + printf '%s' "$candidate" + return 0 + fi + candidate="${NEKO_WEBRTC_NAT1TO1:-}" + if [ -n "$candidate" ] && neko_nat1to1_is_usable "$candidate"; then + iface="$(neko_nat1to1_iface_for_ip "$candidate")" + if neko_nat1to1_is_overlay_iface "$iface"; then + printf '%s' "$candidate" + return 0 + fi + fi + ;; + *) + [ -n "$lan_ip" ] && printf '%s' "$lan_ip" + return 0 + ;; + esac + [ -n "$lan_ip" ] && printf '%s' "$lan_ip" +} + configure_mdns() { if [ "${ENABLE_MDNS:-1}" != "1" ]; then return 0 @@ -2246,8 +2293,9 @@ install_neko_browser() { export NEKO_WEBRTC_UDPMUX_1="${NEKO_WEBRTC_UDPMUX_1:-$NEKO_WEBRTC_UDPMUX}" export NEKO_WEBRTC_UDPMUX_2="${NEKO_WEBRTC_UDPMUX_2:-52301}" export NEKO_WEBRTC_UDPMUX_3="${NEKO_WEBRTC_UDPMUX_3:-52302}" - if ! neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then - export NEKO_WEBRTC_NAT1TO1="$(detect_preferred_lan_ip || true)" + target_nat1to1="$(resolve_neko_nat1to1)" + if [ -n "$target_nat1to1" ]; then + export NEKO_WEBRTC_NAT1TO1="$target_nat1to1" fi export NEKO_PLUGINS_ENABLED="${NEKO_PLUGINS_ENABLED:-true}" ensure_neko_browser_launcher_executable @@ -2274,7 +2322,7 @@ install_neko_browser() { } install_redroid() { - if [ "${ENABLE_REDROID:-1}" != "1" ]; then + if [ "${ENABLE_REDROID:-0}" != "1" ]; then return 0 fi if ! have docker; then @@ -2353,7 +2401,7 @@ RULES } install_android_panel() { - if [ "${ENABLE_ANDROID_PANEL:-1}" != "1" ]; then + if [ "${ENABLE_ANDROID_PANEL:-0}" != "1" ]; then return 0 fi log "Installing Android web panel (ws-scrcpy)" @@ -2513,7 +2561,7 @@ UNIT } install_webtty() { - if [ "${ENABLE_WEBTTY:-1}" != "1" ]; then + if [ "${ENABLE_WEBTTY:-0}" != "1" ]; then return 0 fi log "Installing WebTTY" @@ -2625,7 +2673,7 @@ render_homepage_services() { href: http://${HOSTNAME_ALIAS}.local:${PORT} description: Direct access to FastAPI port YAML - if [ "${ENABLE_WEBTTY:-1}" = "1" ]; then + if [ "${ENABLE_WEBTTY:-0}" = "1" ]; then cat >>"$target" <>"$target" <>"$target" <>"$target" <>"$target" <>"$target" <>"$target" <>"$target" <>"$target" <>"$target" <>"$target" </dev/null 2>&1 || true rm -f /etc/systemd/system/live-frigate-usb-watch.service return 0 @@ -3021,7 +3069,7 @@ UNIT } install_pulseaudio_service() { - if [ "${ENABLE_PULSEAUDIO:-1}" != "1" ]; then + if [ "${ENABLE_PULSEAUDIO:-0}" != "1" ]; then return 0 fi log "Installing PulseAudio service" @@ -3084,7 +3132,7 @@ UNIT } prepare_srs() { - if [ "${ENABLE_SRS:-1}" != "1" ] || ! need_docker; then + if [ "${ENABLE_SRS:-0}" != "1" ] || ! need_docker; then return 0 fi log "Starting SRS" diff --git a/d2ypp2/scripts/linux/neko_ip_watch.sh b/d2ypp2/scripts/linux/neko_ip_watch.sh index 4036e36..53414d6 100644 --- a/d2ypp2/scripts/linux/neko_ip_watch.sh +++ b/d2ypp2/scripts/linux/neko_ip_watch.sh @@ -53,13 +53,7 @@ maybe_refresh_neko_for_ip_change() { return 0 fi - preferred="$(detect_preferred_lan_ip || true)" - target="$preferred" - case "${NEKO_ACCESS_MODE:-lan}" in - remote) - target="${NEKO_WEBRTC_NAT1TO1:-}" - ;; - esac + target="$(resolve_neko_nat1to1 || true)" if [ -z "$target" ]; then return 0 fi diff --git a/d2ypp2/scripts/linux/service_ctl.sh b/d2ypp2/scripts/linux/service_ctl.sh index 66c359e..7303e60 100644 --- a/d2ypp2/scripts/linux/service_ctl.sh +++ b/d2ypp2/scripts/linux/service_ctl.sh @@ -109,19 +109,19 @@ NEKO_VIDEO_BITRATE="${NEKO_VIDEO_BITRATE:-1200}" NEKO_BROWSER_RENDER_MODE="${NEKO_BROWSER_RENDER_MODE:-auto}" NEKO_TAMPERMONKEY_REPAIR="${NEKO_TAMPERMONKEY_REPAIR:-1}" ENABLE_NEKO="${ENABLE_NEKO:-1}" -ENABLE_MITMPROXY="${ENABLE_MITMPROXY:-1}" +ENABLE_MITMPROXY="${ENABLE_MITMPROXY:-0}" MITMPROXY_WEB_PORT="${MITMPROXY_WEB_PORT:-8086}" MITMPROXY_PROXY_PORT="${MITMPROXY_PROXY_PORT:-8087}" -ENABLE_VSCODE_SERVER="${ENABLE_VSCODE_SERVER:-1}" +ENABLE_VSCODE_SERVER="${ENABLE_VSCODE_SERVER:-0}" VSCODE_SERVER_PORT="${VSCODE_SERVER_PORT:-8440}" VSCODE_SERVER_PASSWORD="${VSCODE_SERVER_PASSWORD:-12345678}" -ENABLE_UPTIME_KUMA="${ENABLE_UPTIME_KUMA:-1}" +ENABLE_UPTIME_KUMA="${ENABLE_UPTIME_KUMA:-0}" UPTIME_KUMA_PORT="${UPTIME_KUMA_PORT:-3001}" -ENABLE_PULSEAUDIO="${ENABLE_PULSEAUDIO:-1}" +ENABLE_PULSEAUDIO="${ENABLE_PULSEAUDIO:-0}" PULSEAUDIO_TCP_PORT="${PULSEAUDIO_TCP_PORT:-4713}" ENABLE_KMSCUBE="${ENABLE_KMSCUBE:-1}" KMSCUBE_DRM_DEVICE="${KMSCUBE_DRM_DEVICE:-/dev/dri/card0}" -ENABLE_OPENCLAW="${ENABLE_OPENCLAW:-1}" +ENABLE_OPENCLAW="${ENABLE_OPENCLAW:-0}" OPENCLAW_IMAGE="${OPENCLAW_IMAGE:-ghcr.io/openclaw/openclaw:latest}" OPENCLAW_GATEWAY_PORT="${OPENCLAW_GATEWAY_PORT:-18789}" OPENCLAW_BRIDGE_PORT="${OPENCLAW_BRIDGE_PORT:-18790}" @@ -129,13 +129,13 @@ OPENCLAW_GATEWAY_TOKEN="${OPENCLAW_GATEWAY_TOKEN:-12345678}" OPENCLAW_ALLOW_INSECURE_PRIVATE_WS="${OPENCLAW_ALLOW_INSECURE_PRIVATE_WS:-1}" OPENCLAW_CONFIG_DIR="${OPENCLAW_CONFIG_DIR:-/var/lib/live-openclaw/config}" OPENCLAW_WORKSPACE_DIR="${OPENCLAW_WORKSPACE_DIR:-/var/lib/live-openclaw/workspace}" -ENABLE_HOMEASSISTANT="${ENABLE_HOMEASSISTANT:-1}" -HOMEASSISTANT_AUTOSTART="${HOMEASSISTANT_AUTOSTART:-1}" +ENABLE_HOMEASSISTANT="${ENABLE_HOMEASSISTANT:-0}" +HOMEASSISTANT_AUTOSTART="${HOMEASSISTANT_AUTOSTART:-0}" HOMEASSISTANT_IMAGE="${HOMEASSISTANT_IMAGE:-ghcr.io/home-assistant/home-assistant:stable}" HOMEASSISTANT_PORT="${HOMEASSISTANT_PORT:-8123}" HOMEASSISTANT_CONFIG_DIR="${HOMEASSISTANT_CONFIG_DIR:-/var/lib/live-homeassistant/config}" -ENABLE_FRIGATE="${ENABLE_FRIGATE:-1}" -FRIGATE_USB_AUTOSTART="${FRIGATE_USB_AUTOSTART:-1}" +ENABLE_FRIGATE="${ENABLE_FRIGATE:-0}" +FRIGATE_USB_AUTOSTART="${FRIGATE_USB_AUTOSTART:-0}" FRIGATE_USB_SCAN_INTERVAL="${FRIGATE_USB_SCAN_INTERVAL:-60}" FRIGATE_IMAGE="${FRIGATE_IMAGE:-ghcr.io/blakeblackshear/frigate:stable}" FRIGATE_WEB_PORT="${FRIGATE_WEB_PORT:-5001}" @@ -150,7 +150,7 @@ WOL_BROADCAST="${WOL_BROADCAST:-255.255.255.255}" WOL_PORT="${WOL_PORT:-9}" WOL_PROBE_INTERVAL="${WOL_PROBE_INTERVAL:-30}" WOL_PROBE_CIDR="${WOL_PROBE_CIDR:-}" -ENABLE_NTFY="${ENABLE_NTFY:-1}" +ENABLE_NTFY="${ENABLE_NTFY:-0}" NTFY_IMAGE="${NTFY_IMAGE:-binwiederhier/ntfy:latest}" NTFY_PORT="${NTFY_PORT:-8089}" NTFY_CONFIG_DIR="${NTFY_CONFIG_DIR:-/var/lib/live-ntfy/config}" @@ -166,7 +166,7 @@ COTURN_MIN_PORT="${COTURN_MIN_PORT:-49160}" COTURN_MAX_PORT="${COTURN_MAX_PORT:-49200}" COTURN_REALM="${COTURN_REALM:-live.local}" COTURN_STATIC_AUTH_SECRET="${COTURN_STATIC_AUTH_SECRET:-}" -ENABLE_REDROID="${ENABLE_REDROID:-1}" +ENABLE_REDROID="${ENABLE_REDROID:-0}" REDROID_DEFAULT_PORT="${REDROID_DEFAULT_PORT:-5555}" REDROID_INSTANCE_PREFIX="${REDROID_INSTANCE_PREFIX:-redroid13}" REDROID_DATA_PREFIX="${REDROID_DATA_PREFIX:-/var/lib/live-redroid}" @@ -970,11 +970,10 @@ hosts.write_text("\\n".join(next_host_lines) + "\\n", encoding="utf-8") PY } -neko_nat1to1_is_usable() { +neko_nat1to1_iface_for_ip() { local candidate="$1" - local iface [ -n "$candidate" ] || return 1 - iface="$(ip -4 addr show 2>/dev/null | awk -v want="$candidate" ' + ip -4 addr show 2>/dev/null | awk -v want="$candidate" ' /^[0-9]+: / { iface=$2 sub(/:$/, "", iface) @@ -987,7 +986,63 @@ neko_nat1to1_is_usable() { exit } } - ')" + ' +} + +neko_nat1to1_is_overlay_iface() { + local iface="${1:-}" + case "$iface" in + ""|lo|docker*|br-*|veth*|virbr*|sit*|dummy*) return 1 ;; + tun*|tap*|zt*|tailscale*|wg*|wireguard*) return 0 ;; + *) return 1 ;; + esac +} + +resolve_neko_nat1to1() { + local mode="${NEKO_ACCESS_MODE:-lan}" candidate="" lan_ip="" iface="" + lan_ip="$(detect_preferred_lan_ip || true)" + case "$mode" in + remote) + # VPN/remote viewers must use the WireGuard overlay address, not the LAN IP. + candidate="${NEKO_WIREGUARD_HOST:-}" + if [ -n "$candidate" ] && neko_nat1to1_is_usable "$candidate"; then + printf '%s' "$candidate" + return 0 + fi + candidate="${NEKO_WEBRTC_NAT1TO1:-}" + if [ -n "$candidate" ] && neko_nat1to1_is_usable "$candidate"; then + iface="$(neko_nat1to1_iface_for_ip "$candidate")" + if neko_nat1to1_is_overlay_iface "$iface"; then + printf '%s' "$candidate" + return 0 + fi + fi + ;; + *) + [ -n "$lan_ip" ] && printf '%s' "$lan_ip" + return 0 + ;; + esac + [ -n "$lan_ip" ] && printf '%s' "$lan_ip" +} + +neko_shellcrash_proxy_port_from_url() { + local url="${1:-}" port="" + port="$(printf '%s' "$url" | sed -n 's|.*:\([0-9][0-9]*\)$|\1|p')" + case "$port" in + "$(shellcrash_neko_proxy_port)"|"$(shellcrash_mix_port)"|"$(shellcrash_redir_port)"|"$(shellcrash_tproxy_port)") + printf '%s' "$port" + return 0 + ;; + esac + return 1 +} + +neko_nat1to1_is_usable() { + local candidate="$1" + local iface + [ -n "$candidate" ] || return 1 + iface="$(neko_nat1to1_iface_for_ip "$candidate")" case "$iface" in ""|lo|docker*|br-*|veth*|virbr*|sit*|dummy*) return 1 @@ -1458,8 +1513,20 @@ resolve_neko_browser_proxy() { ;; ?*) if neko_browser_proxy_url_is_usable "$NEKO_BROWSER_PROXY"; then - printf '%s' "$NEKO_BROWSER_PROXY" - return 0 + if neko_shellcrash_proxy_port_from_url "$NEKO_BROWSER_PROXY" >/dev/null 2>&1; then + local shell_port + shell_port="$(neko_shellcrash_proxy_port_from_url "$NEKO_BROWSER_PROXY")" + if shellcrash_proxy_available "$shell_port"; then + printf '%s' "$NEKO_BROWSER_PROXY" + return 0 + fi + if system_direct_global_ready; then + return 0 + fi + else + printf '%s' "$NEKO_BROWSER_PROXY" + return 0 + fi fi ;; esac @@ -1486,7 +1553,6 @@ resolve_neko_browser_proxy() { } service_neko_reconfigure_for_shellcrash_change() { - neko_browser_proxy_switch_enabled || return 0 case "$SHELLCRASH_ATTACH_NEKO" in 0|false|FALSE|off|OFF|none|NONE|direct|DIRECT) return 0 @@ -1494,6 +1560,19 @@ service_neko_reconfigure_for_shellcrash_change() { esac have docker || return 0 docker ps --format '{{.Names}}' 2>/dev/null | grep -Eq '^live-neko-[0-9]+$' || return 0 + if ! shellcrash_proxy_available "$(shellcrash_neko_proxy_port)"; then + case "${NEKO_BROWSER_PROXY:-}" in + ""|0|false|FALSE|off|OFF|none|NONE|direct|DIRECT) ;; + *) + if system_direct_global_ready || ! shellcrash_proxy_available "$(shellcrash_mix_port)"; then + stack_env_upsert NEKO_BROWSER_PROXY "" + stack_env_upsert ENABLE_NEKO_BROWSER_PROXY 0 + export NEKO_BROWSER_PROXY="" + export ENABLE_NEKO_BROWSER_PROXY=0 + fi + ;; + esac + fi service_neko_reconfigure >/dev/null 2>&1 || true } @@ -2290,10 +2369,10 @@ service_neko_status() { local port network_ok port_ok http_code runtime_ok instance_count="$(resolve_neko_instance_count)" total_count="$instance_count" - if ! neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then - NEKO_WEBRTC_NAT1TO1="$(detect_preferred_lan_ip || true)" + target_nat1to1="$(resolve_neko_nat1to1)" + if [ -n "$target_nat1to1" ] && [ "${NEKO_WEBRTC_NAT1TO1:-}" != "$target_nat1to1" ]; then + NEKO_WEBRTC_NAT1TO1="$target_nat1to1" fi - target_nat1to1="${NEKO_WEBRTC_NAT1TO1:-}" for idx in $(seq 1 "$instance_count"); do name="live-neko-$idx" port="$(resolve_neko_http_port_for_instance "$idx")" @@ -2483,8 +2562,12 @@ export_neko_env() { export NEKO_WEBRTC_UDPMUX_1="${NEKO_WEBRTC_UDPMUX_1:-$NEKO_WEBRTC_UDPMUX}" export NEKO_WEBRTC_UDPMUX_2="${NEKO_WEBRTC_UDPMUX_2:-52301}" export NEKO_WEBRTC_UDPMUX_3="${NEKO_WEBRTC_UDPMUX_3:-52302}" - if ! neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then - export NEKO_WEBRTC_NAT1TO1="$(detect_preferred_lan_ip || true)" + target_nat1to1="$(resolve_neko_nat1to1)" + if [ -n "$target_nat1to1" ]; then + if [ "${NEKO_WEBRTC_NAT1TO1:-}" != "$target_nat1to1" ]; then + stack_env_upsert NEKO_WEBRTC_NAT1TO1 "$target_nat1to1" + fi + export NEKO_WEBRTC_NAT1TO1="$target_nat1to1" fi export NEKO_PLUGINS_ENABLED="${NEKO_PLUGINS_ENABLED:-true}" } @@ -2502,7 +2585,7 @@ service_neko_stop() { } service_mitmproxy_status() { - if [ "${ENABLE_MITMPROXY:-1}" != "1" ]; then + if [ "${ENABLE_MITMPROXY:-0}" != "1" ]; then kv available 0 kv running 0 kv status unavailable @@ -2538,7 +2621,7 @@ service_mitmproxy_stop() { } service_vscode_server_status() { - if [ "${ENABLE_VSCODE_SERVER:-1}" != "1" ]; then + if [ "${ENABLE_VSCODE_SERVER:-0}" != "1" ]; then kv available 0 kv running 0 kv status unavailable @@ -2574,7 +2657,7 @@ service_vscode_server_stop() { } service_uptime_kuma_status() { - if [ "${ENABLE_UPTIME_KUMA:-1}" != "1" ]; then + if [ "${ENABLE_UPTIME_KUMA:-0}" != "1" ]; then kv available 0 kv running 0 kv status unavailable @@ -2610,7 +2693,7 @@ service_uptime_kuma_stop() { } service_pulseaudio_status() { - if [ "${ENABLE_PULSEAUDIO:-1}" != "1" ]; then + if [ "${ENABLE_PULSEAUDIO:-0}" != "1" ]; then kv available 0 kv running 0 kv status unavailable @@ -2678,7 +2761,7 @@ service_kmscube_stop() { } service_openclaw_status() { - if [ "${ENABLE_OPENCLAW:-1}" != "1" ]; then + if [ "${ENABLE_OPENCLAW:-0}" != "1" ]; then kv available 0 kv running 0 kv status unavailable @@ -2715,7 +2798,7 @@ service_openclaw_stop() { } service_homeassistant_status() { - if [ "${ENABLE_HOMEASSISTANT:-1}" != "1" ]; then + if [ "${ENABLE_HOMEASSISTANT:-0}" != "1" ]; then kv available 0 kv running 0 kv status unavailable @@ -2939,7 +3022,7 @@ ensure_frigate_default_config() { } service_frigate_status() { - if [ "${ENABLE_FRIGATE:-1}" != "1" ]; then + if [ "${ENABLE_FRIGATE:-0}" != "1" ]; then kv available 0 kv running 0 kv status unavailable @@ -2989,7 +3072,7 @@ service_frigate_stop() { } service_frigate_auto() { - if [ "${ENABLE_FRIGATE:-1}" != "1" ] || [ "${FRIGATE_USB_AUTOSTART:-1}" != "1" ]; then + if [ "${ENABLE_FRIGATE:-0}" != "1" ] || [ "${FRIGATE_USB_AUTOSTART:-0}" != "1" ]; then kv message "Frigate USB autostart disabled" return 0 fi @@ -3080,7 +3163,7 @@ ensure_ntfy_default_config() { } service_ntfy_status() { - if [ "${ENABLE_NTFY:-1}" != "1" ]; then + if [ "${ENABLE_NTFY:-0}" != "1" ]; then kv available 0 kv running 0 kv status unavailable @@ -3282,7 +3365,7 @@ redroid_container_matches_host_support() { } service_redroid_status() { - if [ "${ENABLE_REDROID:-1}" != "1" ]; then + if [ "${ENABLE_REDROID:-0}" != "1" ]; then kv available 0 kv running 0 kv status unavailable @@ -3321,7 +3404,7 @@ service_redroid_status() { } service_redroid_start() { - if [ "${ENABLE_REDROID:-1}" != "1" ]; then + if [ "${ENABLE_REDROID:-0}" != "1" ]; then kv message "Set ENABLE_REDROID=1 first" exit 1 fi diff --git a/d2ypp2/scripts/linux/stop_optional_hub_services.sh b/d2ypp2/scripts/linux/stop_optional_hub_services.sh new file mode 100644 index 0000000..74f6569 --- /dev/null +++ b/d2ypp2/scripts/linux/stop_optional_hub_services.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Stop optional hub modules that compete with streaming CPU. +# Defaults are ENABLE_*=0 in system-stack.env.example; console Start still works. +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)" +cd "$ROOT_DIR" +. scripts/linux/lib/common.sh +load_env + +STACK_ENV="$ROOT_DIR/config/system-stack.env" +mkdir -p "$(dirname "$STACK_ENV")" + +stack_env_upsert() { + local key="$1" value="$2" + touch "$STACK_ENV" + if grep -q "^${key}=" "$STACK_ENV" 2>/dev/null; then + sed -i "s/^${key}=.*/${key}=${value}/" "$STACK_ENV" + else + printf '%s=%s\n' "$key" "$value" >>"$STACK_ENV" + fi +} + +OPTIONAL_KEYS=( + ENABLE_REDROID + ENABLE_FRIGATE + FRIGATE_USB_AUTOSTART + ENABLE_HOMEASSISTANT + HOMEASSISTANT_AUTOSTART + ENABLE_OPENCLAW + ENABLE_SRS + ENABLE_MITMPROXY + ENABLE_VSCODE_SERVER + ENABLE_HOMEPAGE + ENABLE_FILEBROWSER + ENABLE_UPTIME_KUMA + ENABLE_NTFY + ENABLE_ANDROID_PANEL + ENABLE_WEBTTY + ENABLE_PULSEAUDIO +) + +for key in "${OPTIONAL_KEYS[@]}"; do + stack_env_upsert "$key" "0" +done + +CTL="$ROOT_DIR/scripts/linux/service_ctl.sh" +for svc in redroid frigate homeassistant openclaw srs mitmproxy vscode_server homepage filebrowser uptime_kuma ntfy android_panel webtty pulseaudio; do + bash "$CTL" "$svc" stop >/dev/null 2>&1 || true +done + +for unit in live-redroid-host.service live-frigate-usb-watch.service live-android-panel.service live-webtty.service live-pulseaudio.service; do + systemctl disable --now "$unit" >/dev/null 2>&1 || true +done + +# Belt-and-suspenders: stop leftover optional containers (compose project prefixes vary). +OPTIONAL_PATTERNS='live-frigate|live-homeassistant|live-openclaw|live-srs|live-mitmproxy|live-code-server|live-homepage|live-filebrowser|live-uptime-kuma|live-ntfy|redroid' +mapfile -t _left < <(docker ps --format '{{.Names}}' 2>/dev/null | grep -E "$OPTIONAL_PATTERNS" || true) +if [ "${#_left[@]}" -gt 0 ]; then + docker stop "${_left[@]}" >/dev/null 2>&1 || true +fi + +echo "[optional-stop] disabled optional hub modules in $STACK_ENV" +docker ps --format '{{.Names}}' 2>/dev/null | grep -E '^live-neko-[0-9]+$' | sort -V || true +uptime diff --git a/d2ypp2/src/hub_routes.py b/d2ypp2/src/hub_routes.py index 72a9e1b..ffaecb3 100644 --- a/d2ypp2/src/hub_routes.py +++ b/d2ypp2/src/hub_routes.py @@ -49,6 +49,12 @@ from src.youtube_live_store import ( list_live_events, youtube_live_summary, ) +from src.youtube_relay_log import ( + get_relay_cover_path, + get_relay_session, + import_relay_sessions_for_process, + list_relay_sessions, +) router = APIRouter(prefix="/hub", tags=["无人直播系统"]) @@ -166,7 +172,8 @@ def _youtube_url_lines_for_process(name: str) -> str: return "" try: _, url_path = resolve_youtube_style_config_paths(_repo_root, name) - return url_path.read_text(encoding="utf-8", errors="ignore") if url_path.is_file() else "" + url_file = Path(url_path) + return url_file.read_text(encoding="utf-8", errors="ignore") if url_file.is_file() else "" except OSError: return "" @@ -535,6 +542,49 @@ async def hub_youtube_live_ingest(payload: dict[str, Any]) -> dict[str, Any]: return await asyncio.to_thread(ingest_browser_telemetry, payload) +@router.get("/youtube/relay/sessions") +async def hub_youtube_relay_sessions( + process: str = "", + q: str = "", + date_from: str = "", + date_to: str = "", + status: str = "", + limit: int = 50, + offset: int = 0, +) -> dict[str, Any]: + return await asyncio.to_thread( + list_relay_sessions, + process=process, + q=q, + date_from=date_from, + date_to=date_to, + status=status, + limit=limit, + offset=offset, + ) + + +@router.get("/youtube/relay/sessions/{session_id}") +async def hub_youtube_relay_session_detail(session_id: str) -> dict[str, Any]: + session = await asyncio.to_thread(get_relay_session, session_id) + if not session: + raise HTTPException(status_code=404, detail="relay session not found") + return {"session": session} + + +@router.post("/youtube/relay/sessions/import-log") +async def hub_youtube_relay_sessions_import_log(body: dict[str, Any]) -> dict[str, Any]: + process = str(body.get("process") or "youtube") + out_path = str(body.get("log_path") or "").strip() or None + replace_imported = bool(body.get("replace_imported")) + return await asyncio.to_thread( + import_relay_sessions_for_process, + process, + out_path=out_path, + replace_imported=replace_imported, + ) + + @router.get("/services/declared") async def hub_services_declared() -> dict[str, Any]: return {"services": services_config_list()} diff --git a/d2ypp2/src/youtube_relay_log.py b/d2ypp2/src/youtube_relay_log.py new file mode 100644 index 0000000..02dff3a --- /dev/null +++ b/d2ypp2/src/youtube_relay_log.py @@ -0,0 +1,1047 @@ +from __future__ import annotations + +import json +import os +import re +import subprocess +import threading +import time +import uuid +from datetime import datetime +from pathlib import Path +from typing import Any + +from src.douyin_source_display import ( + _entry_for_title, + _url_entries_from_lines, + extract_douyin_source_meta, +) +from src.youtube_live_store import _connect, extract_first_url, extract_source_room_id, extract_youtube_key_suffix + +_RELAY_SESSIONS_TABLE = "youtube_relay_sessions" +_RECORDING_LINE_RE = re.compile( + r"正在录制\s*\d+\s*(?:个|路)\s*[::]\s*([^[\n]+?)\[原画\s*([0-9:]+)\]", + re.IGNORECASE, +) +_PUSH_START_RE = re.compile(r"开始推流到 YouTube:\s*(.+?)\s*$") +_STREAM_TITLE_TS_RE = re.compile(r"_(?P\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})$") +_LOG_TS_RE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}):") +_INCOMING_URL_RE = re.compile(r"传入地址:\s*(https?://\S+)", re.IGNORECASE) +_FAIL_ADDR_RE = re.compile( + r"获取失败的地址是:\('原画',\s*'(https?://[^']+)',\s*'主播:\s*([^']+)'\)" +) +_ANCHOR_LABEL_RE = re.compile(r"主播[::]\s*([^\s'\"()]+)") + +_ACTIVE_BY_PROCESS: dict[str, int] = {} + + +def _json_dumps(value: Any) -> str: + return json.dumps(value, ensure_ascii=False, separators=(",", ":"), default=str) + + +def _json_loads(raw: str | None, fallback: Any) -> Any: + if not raw: + return fallback + try: + return json.loads(raw) + except json.JSONDecodeError: + return fallback + + +def _normalize_process(process: str) -> str: + return (process or "").strip() or "youtube" + + +def _covers_dir(base_dir: Path | None = None) -> Path: + root = base_dir or Path(os.environ.get("LIVE_PROJECT_ROOT") or Path(__file__).resolve().parent.parent) + path = root / "runtime" / "youtube_relay" / "covers" + path.mkdir(parents=True, exist_ok=True) + return path + + +def _ensure_schema(conn) -> None: + conn.execute( + f""" + CREATE TABLE IF NOT EXISTS {_RELAY_SESSIONS_TABLE} ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_uuid TEXT NOT NULL UNIQUE, + process TEXT NOT NULL DEFAULT '', + channel_name TEXT NOT NULL DEFAULT '', + anchor_name TEXT NOT NULL DEFAULT '', + source_url TEXT NOT NULL DEFAULT '', + source_room_id TEXT NOT NULL DEFAULT '', + stream_title TEXT NOT NULL DEFAULT '', + youtube_key_suffix TEXT NOT NULL DEFAULT '', + started_at REAL NOT NULL, + ended_at REAL, + duration_seconds REAL NOT NULL DEFAULT 0, + push_date TEXT NOT NULL DEFAULT '', + cover_path TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'active', + end_reason TEXT NOT NULL DEFAULT '', + metadata_json TEXT NOT NULL DEFAULT '{{}}', + created_at REAL NOT NULL, + updated_at REAL NOT NULL + ) + """ + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_relay_sessions_process " + f"ON {_RELAY_SESSIONS_TABLE}(process, started_at DESC)" + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_relay_sessions_room " + f"ON {_RELAY_SESSIONS_TABLE}(source_room_id)" + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_relay_sessions_date " + f"ON {_RELAY_SESSIONS_TABLE}(push_date DESC, started_at DESC)" + ) + conn.commit() + + +def _connect_relay(db_path: Path | None = None): + conn = _connect(db_path) + _ensure_schema(conn) + return conn + + +def _row_to_session(row) -> dict[str, Any]: + data = dict(row) + data["metadata"] = _json_loads(data.pop("metadata_json", "{}"), {}) + stored_duration = int(float(data.get("duration_seconds") or 0)) + if data.get("ended_at"): + data["duration_seconds"] = stored_duration + elif stored_duration > 0: + data["duration_seconds"] = stored_duration + else: + data["duration_seconds"] = int(max(0, time.time() - float(data.get("started_at") or time.time()))) + data["cover_url"] = f"/hub/youtube/relay/sessions/{data['id']}/cover" if data.get("cover_path") else "" + return data + + +def _push_date_from_ts(ts: float) -> str: + return datetime.fromtimestamp(ts).strftime("%Y-%m-%d") + + +def _parse_stream_title(stream_title: str) -> tuple[str, str]: + title = (stream_title or "").strip() + match = _STREAM_TITLE_TS_RE.search(title) + if not match: + return title, "" + anchor = title[: match.start()].rstrip("_") + stamp = match.group("ts") + push_date = stamp.split("_", 1)[0] if "_" in stamp else "" + return anchor, push_date + + +def _timestamp_from_stream_title(stream_title: str) -> float | None: + match = _STREAM_TITLE_TS_RE.search(stream_title or "") + if not match: + return None + try: + return datetime.strptime(match.group("ts"), "%Y-%m-%d_%H-%M-%S").timestamp() + except ValueError: + return None + + +def _parse_log_line_ts(line: str) -> float | None: + match = _LOG_TS_RE.match(line.strip()) + if not match: + return None + try: + return datetime.strptime(match.group(1), "%Y-%m-%dT%H:%M:%S").timestamp() + except ValueError: + return None + + +def _parse_local_wall_time(line: str, log_ts: float | None) -> float | None: + if log_ts is None: + return None + local_hms = "" + for part in reversed(line.split("|")): + token = part.strip() + if re.fullmatch(r"\d{2}:\d{2}:\d{2}", token): + local_hms = token + break + if not local_hms: + return log_ts + try: + base = datetime.fromtimestamp(log_ts) + hour, minute, second = (int(x) for x in local_hms.split(":")) + return base.replace(hour=hour, minute=minute, second=second, microsecond=0).timestamp() + except (ValueError, OSError): + return log_ts + + +def _clean_douyin_url(url: str) -> str: + return extract_first_url(url) or "" + + +def _build_anchor_url_index(url_lines: str) -> dict[str, tuple[str, str]]: + index: dict[str, tuple[str, str]] = {} + for entry in _url_entries_from_lines(url_lines): + title = (entry.get("source_title") or "").strip() + url = _clean_douyin_url(entry.get("source_url") or "") + room_id = entry.get("room_id") or "" + if title and url: + index[title] = (url, room_id) + return index + + +def _resolve_anchor_url( + anchor: str, + url_index: dict[str, tuple[str, str]], + url_lines: str, + log_url_index: dict[str, tuple[str, str]] | None = None, +) -> tuple[str, str]: + name = (anchor or "").strip() + if not name: + return "", "" + if log_url_index and name in log_url_index: + return log_url_index[name] + entry = _entry_for_title(_url_entries_from_lines(url_lines), name) + if entry: + return _clean_douyin_url(entry["source_url"]), entry["room_id"] + if name in url_index: + url, room_id = url_index[name] + return _clean_douyin_url(url), room_id + meta = extract_douyin_source_meta(url_lines, name) + url = _clean_douyin_url(str(meta.get("source_url") or "")) + room_id = str(meta.get("source_room_id") or "") + if url: + return url, room_id + return _lookup_room_id(name, url_lines) + + +def _parse_duration_token(token: str) -> int: + parts = [int(part) for part in (token or "0").split(":")] + if len(parts) == 3: + return parts[0] * 3600 + parts[1] * 60 + parts[2] + if len(parts) == 2: + return parts[0] * 60 + parts[1] + return 0 + + +def _lookup_room_id(anchor_name: str, url_lines: str) -> tuple[str, str]: + anchor = (anchor_name or "").strip() + for line in (url_lines or "").splitlines(): + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + if anchor and anchor not in stripped: + continue + url = extract_first_url(stripped) + room_id = extract_source_room_id(stripped, url) + if url: + return url, room_id + meta = extract_douyin_source_meta(url_lines, anchor) + return str(meta.get("source_url") or ""), str(meta.get("source_room_id") or "") + + +def _close_session_row( + conn, + row_id: int, + *, + ended_at: float | None = None, + reason: str = "", + duration_seconds: int | None = None, +) -> None: + row = conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (row_id,)).fetchone() + if not row or row["ended_at"]: + return + end = float(ended_at or time.time()) + duration = duration_seconds + if duration is None: + duration = int(max(0, end - float(row["started_at"]))) + conn.execute( + f""" + UPDATE {_RELAY_SESSIONS_TABLE} + SET ended_at = ?, duration_seconds = ?, status = 'ended', end_reason = ?, updated_at = ? + WHERE id = ? + """, + (end, int(duration), (reason or "")[:500], end, row_id), + ) + process = str(row["process"] or "") + if _ACTIVE_BY_PROCESS.get(process) == row_id: + _ACTIVE_BY_PROCESS.pop(process, None) + + +def close_active_relay_sessions( + process: str, + *, + reason: str = "", + ended_at: float | None = None, + db_path: Path | None = None, +) -> list[dict[str, Any]]: + proc = _normalize_process(process) + conn = _connect_relay(db_path) + try: + rows = conn.execute( + f"SELECT id FROM {_RELAY_SESSIONS_TABLE} WHERE process = ? AND ended_at IS NULL ORDER BY started_at DESC", + (proc,), + ).fetchall() + for row in rows: + _close_session_row(conn, int(row["id"]), ended_at=ended_at, reason=reason) + conn.commit() + if not rows: + return [] + ids = [int(row["id"]) for row in rows] + return [ + _row_to_session(item) + for item in conn.execute( + f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id IN ({','.join('?' * len(ids))})", + ids, + ).fetchall() + ] + finally: + conn.close() + + +def start_relay_session( + *, + process: str, + anchor_name: str, + source_url: str = "", + source_room_id: str = "", + stream_title: str = "", + channel_name: str = "", + youtube_key_suffix: str = "", + metadata: dict[str, Any] | None = None, + capture_cover_url: str = "", + db_path: Path | None = None, +) -> dict[str, Any]: + proc = _normalize_process(process) + now = time.time() + anchor = (anchor_name or "").strip() + if not source_url: + source_url = extract_first_url(stream_title) + if not source_room_id: + source_room_id = extract_source_room_id(source_url, anchor_name, stream_title) + conn = _connect_relay(db_path) + try: + open_rows = conn.execute( + f"SELECT id, anchor_name FROM {_RELAY_SESSIONS_TABLE} WHERE process = ? AND ended_at IS NULL", + (proc,), + ).fetchall() + for row in open_rows: + if str(row["anchor_name"] or "").strip() == anchor and anchor: + session = _row_to_session( + conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (int(row["id"]),)).fetchone() + ) + conn.commit() + return session + _close_session_row(conn, int(row["id"]), ended_at=now, reason="source_switch") + session_uuid = str(uuid.uuid4()) + push_date = _push_date_from_ts(now) + _, title_date = _parse_stream_title(stream_title) + if title_date: + push_date = title_date + title_started = _timestamp_from_stream_title(stream_title) + if title_started: + now = title_started + conn.execute( + f""" + INSERT INTO {_RELAY_SESSIONS_TABLE}( + session_uuid, process, channel_name, anchor_name, source_url, source_room_id, + stream_title, youtube_key_suffix, started_at, duration_seconds, push_date, + cover_path, status, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, '', 'active', ?, ?, ?) + """, + ( + session_uuid, + proc, + channel_name or "", + anchor, + source_url or "", + source_room_id or "", + stream_title or "", + youtube_key_suffix or "", + now, + push_date, + _json_dumps(metadata or {}), + now, + now, + ), + ) + session_id = int(conn.execute("SELECT last_insert_rowid()").fetchone()[0]) + _ACTIVE_BY_PROCESS[proc] = session_id + conn.commit() + session = _row_to_session( + conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (session_id,)).fetchone() + ) + finally: + conn.close() + cover_url = capture_cover_url or source_url + if cover_url: + threading.Thread( + target=_capture_cover_safe, + args=(session["id"], cover_url, db_path), + daemon=True, + ).start() + return session + + +def end_relay_session( + process: str, + *, + anchor_name: str = "", + reason: str = "", + ended_at: float | None = None, + db_path: Path | None = None, +) -> dict[str, Any] | None: + proc = _normalize_process(process) + conn = _connect_relay(db_path) + try: + if anchor_name.strip(): + row = conn.execute( + f""" + SELECT id FROM {_RELAY_SESSIONS_TABLE} + WHERE process = ? AND ended_at IS NULL AND anchor_name = ? + ORDER BY started_at DESC LIMIT 1 + """, + (proc, anchor_name.strip()), + ).fetchone() + else: + row = conn.execute( + f""" + SELECT id FROM {_RELAY_SESSIONS_TABLE} + WHERE process = ? AND ended_at IS NULL + ORDER BY started_at DESC LIMIT 1 + """, + (proc,), + ).fetchone() + if not row: + conn.commit() + return None + _close_session_row(conn, int(row["id"]), ended_at=ended_at, reason=reason or "ended") + conn.commit() + closed = conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (int(row["id"]),)).fetchone() + return _row_to_session(closed) if closed else None + finally: + conn.close() + + +def on_relay_push_start( + *, + process: str, + anchor_name: str, + record_url: str | None, + stream_title: str, + real_url: str, + channel_name: str = "", + youtube_ini_text: str = "", + db_path: Path | None = None, +) -> dict[str, Any]: + source_url = (record_url or "").strip() or extract_first_url(record_url or "") + if not source_url and real_url: + source_url = real_url + room_id = extract_source_room_id(record_url or "", real_url or "", anchor_name) + return start_relay_session( + process=process, + anchor_name=anchor_name, + source_url=source_url, + source_room_id=room_id, + stream_title=stream_title, + channel_name=channel_name, + youtube_key_suffix=extract_youtube_key_suffix(youtube_ini_text), + metadata={"real_url": real_url, "record_url": record_url or ""}, + capture_cover_url=real_url or source_url, + db_path=db_path, + ) + + +def on_relay_push_end( + process: str, + *, + anchor_name: str, + reason: str = "push_stopped", + db_path: Path | None = None, +) -> dict[str, Any] | None: + return end_relay_session(process, anchor_name=anchor_name, reason=reason, db_path=db_path) + + +def sync_relay_from_recent_log( + process: str, + recent_log: str, + *, + channel_name: str = "", + url_lines: str = "", + db_path: Path | None = None, +) -> dict[str, Any] | None: + proc = _normalize_process(process) + anchor = "" + duration_token = "" + for line in reversed((recent_log or "").splitlines()): + match = _RECORDING_LINE_RE.search(line) + if match: + anchor = match.group(1).strip(" :?") + duration_token = match.group(2).strip() + break + if not anchor: + if "无录制任务" in (recent_log or "")[-2000:]: + closed = close_active_relay_sessions(proc, reason="idle", db_path=db_path) + return {"closed": closed} + return None + source_url, room_id = _lookup_room_id(anchor, url_lines) + if not source_url: + meta = extract_douyin_source_meta(url_lines, recent_log) + source_url = str(meta.get("source_url") or "") + room_id = str(meta.get("source_room_id") or room_id) + conn = _connect_relay(db_path) + try: + row = conn.execute( + f""" + SELECT id, anchor_name FROM {_RELAY_SESSIONS_TABLE} + WHERE process = ? AND ended_at IS NULL + ORDER BY started_at DESC LIMIT 1 + """, + (proc,), + ).fetchone() + if row and str(row["anchor_name"] or "").strip() == anchor: + if duration_token: + duration = _parse_duration_token(duration_token) + conn.execute( + f"UPDATE {_RELAY_SESSIONS_TABLE} SET duration_seconds = ?, updated_at = ? WHERE id = ?", + (duration, time.time(), int(row["id"])), + ) + conn.commit() + return _row_to_session( + conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (int(row["id"]),)).fetchone() + ) + finally: + conn.close() + if row: + end_relay_session(proc, anchor_name=str(row["anchor_name"] or ""), reason="source_switch", db_path=db_path) + session = start_relay_session( + process=proc, + anchor_name=anchor, + source_url=source_url, + source_room_id=room_id, + channel_name=channel_name, + metadata={"sync": "recent_log", "duration_token": duration_token}, + capture_cover_url=source_url, + db_path=db_path, + ) + if duration_token and session.get("id"): + duration = _parse_duration_token(duration_token) + conn = _connect_relay(db_path) + try: + conn.execute( + f"UPDATE {_RELAY_SESSIONS_TABLE} SET duration_seconds = ?, updated_at = ? WHERE id = ?", + (duration, time.time(), int(session["id"])), + ) + conn.commit() + session = _row_to_session( + conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (int(session["id"]),)).fetchone() + ) + finally: + conn.close() + return session + + +def _capture_cover_safe(session_id: int, stream_url: str, db_path: Path | None) -> None: + try: + capture_relay_cover(session_id, stream_url, db_path=db_path) + except Exception: + pass + + +def capture_relay_cover(session_id: int, stream_url: str, *, db_path: Path | None = None) -> str: + url = (stream_url or "").strip() + if not url: + return "" + covers = _covers_dir() + out_path = covers / f"{session_id}.jpg" + headers = ( + "User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15\r\n" + "Referer: https://live.douyin.com/\r\n" + ) + cmd = [ + "ffmpeg", + "-hide_banner", + "-loglevel", + "error", + "-y", + "-headers", + headers, + "-rw_timeout", + "15000000", + "-i", + url, + "-frames:v", + "1", + "-q:v", + "3", + str(out_path), + ] + proc = subprocess.run(cmd, capture_output=True, text=True, timeout=25) + if proc.returncode != 0 or not out_path.is_file() or out_path.stat().st_size < 128: + return "" + conn = _connect_relay(db_path) + try: + conn.execute( + f"UPDATE {_RELAY_SESSIONS_TABLE} SET cover_path = ?, updated_at = ? WHERE id = ?", + (str(out_path), time.time(), session_id), + ) + conn.commit() + finally: + conn.close() + return str(out_path) + + +def get_relay_cover_path(session_id: int | str, *, db_path: Path | None = None) -> Path | None: + conn = _connect_relay(db_path) + try: + row = conn.execute( + f"SELECT cover_path FROM {_RELAY_SESSIONS_TABLE} WHERE id = ? OR session_uuid = ?", + (session_id, str(session_id)), + ).fetchone() + if not row: + return None + path = Path(str(row["cover_path"] or "")) + return path if path.is_file() else None + finally: + conn.close() + + +def list_relay_sessions( + *, + process: str = "", + q: str = "", + date_from: str = "", + date_to: str = "", + status: str = "", + limit: int = 50, + offset: int = 0, + db_path: Path | None = None, +) -> dict[str, Any]: + clauses: list[str] = [] + params: list[Any] = [] + if process: + clauses.append("process = ?") + params.append(_normalize_process(process)) + if status == "active": + clauses.append("ended_at IS NULL") + elif status == "ended": + clauses.append("ended_at IS NOT NULL") + if date_from: + clauses.append("push_date >= ?") + params.append(date_from.strip()) + if date_to: + clauses.append("push_date <= ?") + params.append(date_to.strip()) + if q.strip(): + like = f"%{q.strip()}%" + clauses.append( + "(anchor_name LIKE ? OR source_url LIKE ? OR source_room_id LIKE ? OR stream_title LIKE ? OR channel_name LIKE ?)" + ) + params.extend([like, like, like, like, like]) + where = "WHERE " + " AND ".join(clauses) if clauses else "" + safe_limit = max(1, min(int(limit), 200)) + safe_offset = max(0, int(offset)) + conn = _connect_relay(db_path) + try: + rows = conn.execute( + f"SELECT * FROM {_RELAY_SESSIONS_TABLE} {where} ORDER BY started_at DESC LIMIT ? OFFSET ?", + (*params, safe_limit, safe_offset), + ).fetchall() + total = conn.execute(f"SELECT COUNT(*) FROM {_RELAY_SESSIONS_TABLE} {where}", params).fetchone()[0] + return { + "sessions": [_row_to_session(row) for row in rows], + "total": int(total), + "limit": safe_limit, + "offset": safe_offset, + } + finally: + conn.close() + + +def get_relay_session(session_id: int | str, *, db_path: Path | None = None) -> dict[str, Any]: + conn = _connect_relay(db_path) + try: + row = conn.execute( + f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ? OR session_uuid = ?", + (session_id, str(session_id)), + ).fetchone() + return _row_to_session(row) if row else {} + finally: + conn.close() + + +def clear_imported_relay_sessions(process: str, *, db_path: Path | None = None) -> int: + proc = _normalize_process(process) + conn = _connect_relay(db_path) + try: + cur = conn.execute( + f"DELETE FROM {_RELAY_SESSIONS_TABLE} WHERE process = ? AND end_reason = 'imported_from_log'", + (proc,), + ) + conn.commit() + return int(cur.rowcount or 0) + finally: + conn.close() + + +def _finalize_import_payload(payload: dict[str, Any]) -> dict[str, Any]: + started_at = float(payload.get("started_at") or 0) + duration = int(payload.get("duration_seconds") or 0) + ended_at = payload.get("ended_at") + if ended_at is None and duration > 0 and started_at > 0: + ended_at = started_at + duration + payload["ended_at"] = ended_at + payload["duration_seconds"] = duration + return payload + + +def _new_import_payload( + *, + process: str, + anchor_name: str, + stream_title: str = "", + started_at: float, + push_date: str = "", + source_url: str = "", + source_room_id: str = "", + duration_seconds: int = 0, + youtube_key_suffix: str = "", +) -> dict[str, Any]: + anchor = (anchor_name or "").strip() + title = (stream_title or "").strip() + if not push_date: + _, push_date = _parse_stream_title(title) + if not push_date and started_at: + push_date = _push_date_from_ts(started_at) + return { + "process": process, + "anchor_name": anchor, + "stream_title": title, + "started_at": started_at, + "push_date": push_date, + "source_url": source_url, + "source_room_id": source_room_id, + "duration_seconds": duration_seconds, + "youtube_key_suffix": youtube_key_suffix, + "ended_at": None, + } + + +def _load_process_config_texts(process: str, root: Path) -> tuple[str, str, str]: + from src.youtube_config_paths import resolve_youtube_style_config_paths + + youtube_ini, url_config = resolve_youtube_style_config_paths(root, process) + youtube_ini_text = "" + url_lines = "" + youtube_key_suffix = "" + youtube_path = Path(youtube_ini) + if youtube_path.is_file(): + youtube_ini_text = youtube_path.read_text(encoding="utf-8-sig", errors="replace") + youtube_key_suffix = extract_youtube_key_suffix(youtube_ini_text) + url_path = Path(url_config) + if url_path.is_file(): + url_lines = url_path.read_text(encoding="utf-8-sig", errors="replace") + return url_lines, youtube_ini_text, youtube_key_suffix + + +def import_relay_sessions_from_log( + log_path: str | Path, + *, + process: str = "youtube", + url_lines: str = "", + youtube_key_suffix: str = "", + replace_imported: bool = False, + db_path: Path | None = None, +) -> dict[str, Any]: + path = Path(log_path) + if not path.is_file(): + return {"imported": 0, "closed": 0, "error": "log file not found"} + text = path.read_text(encoding="utf-8", errors="replace") + proc = _normalize_process(process) + if replace_imported: + removed = clear_imported_relay_sessions(proc, db_path=db_path) + else: + removed = 0 + url_index = _build_anchor_url_index(url_lines) + log_url_index: dict[str, tuple[str, str]] = {} + for raw_line in text.splitlines(): + fail_match = _FAIL_ADDR_RE.search(raw_line) + if fail_match: + url = _clean_douyin_url(fail_match.group(1)) + anchor = fail_match.group(2).strip() + if url and anchor: + log_url_index[anchor] = (url, extract_source_room_id(url)) + incoming = _INCOMING_URL_RE.search(raw_line) + if incoming: + url = _clean_douyin_url(incoming.group(1)) + if url: + log_url_index.setdefault("__last_incoming__", (url, extract_source_room_id(url))) + imported = 0 + closed = 0 + active: dict[str, Any] | None = None + sessions: list[dict[str, Any]] = [] + conn = _connect_relay(db_path) + try: + for raw_line in text.splitlines(): + line = raw_line.strip() + if not line: + continue + log_ts = _parse_log_line_ts(line) + event_ts = _parse_local_wall_time(line, log_ts) or log_ts + + incoming = _INCOMING_URL_RE.search(line) + if incoming: + url = _clean_douyin_url(incoming.group(1)) + room_id = extract_source_room_id(url) + log_url_index["__last_incoming__"] = (url, room_id) + label = _ANCHOR_LABEL_RE.search(line) + if label: + log_url_index[label.group(1).strip()] = (url, room_id) + elif active and not active.get("source_url"): + active["source_url"] = url + active["source_room_id"] = room_id + continue + + fail_match = _FAIL_ADDR_RE.search(line) + if fail_match: + url = _clean_douyin_url(fail_match.group(1)) + anchor = fail_match.group(2).strip() + if url and anchor: + log_url_index[anchor] = (url, extract_source_room_id(url)) + continue + + push_match = _PUSH_START_RE.search(line) + if push_match: + stream_title = push_match.group(1).strip() + anchor, push_date = _parse_stream_title(stream_title) + started_at = _timestamp_from_stream_title(stream_title) or event_ts or time.time() + if active: + sessions.append(_finalize_import_payload(active)) + closed += 1 + source_url, source_room_id = _resolve_anchor_url(anchor, url_index, url_lines, log_url_index) + active = _new_import_payload( + process=proc, + anchor_name=anchor, + stream_title=stream_title, + started_at=started_at, + push_date=push_date, + source_url=source_url, + source_room_id=source_room_id, + youtube_key_suffix=youtube_key_suffix, + ) + continue + + rec_match = _RECORDING_LINE_RE.search(line) + if rec_match: + anchor = rec_match.group(1).strip(" :?") + duration = _parse_duration_token(rec_match.group(2).strip()) + if active and str(active.get("anchor_name") or "") == anchor: + active["duration_seconds"] = max(int(active.get("duration_seconds") or 0), duration) + if not active.get("source_url"): + source_url, source_room_id = _resolve_anchor_url(anchor, url_index, url_lines, log_url_index) + active["source_url"] = source_url + active["source_room_id"] = source_room_id + elif active and str(active.get("anchor_name") or "") != anchor: + sessions.append(_finalize_import_payload(active)) + closed += 1 + started_at = (event_ts or time.time()) - duration if duration else (event_ts or time.time()) + source_url, source_room_id = _resolve_anchor_url(anchor, url_index, url_lines, log_url_index) + active = _new_import_payload( + process=proc, + anchor_name=anchor, + started_at=started_at, + source_url=source_url, + source_room_id=source_room_id, + duration_seconds=duration, + youtube_key_suffix=youtube_key_suffix, + ) + else: + started_at = (event_ts or time.time()) - duration if duration else (event_ts or time.time()) + source_url, source_room_id = _resolve_anchor_url(anchor, url_index, url_lines, log_url_index) + active = _new_import_payload( + process=proc, + anchor_name=anchor, + started_at=started_at, + source_url=source_url, + source_room_id=source_room_id, + duration_seconds=duration, + youtube_key_suffix=youtube_key_suffix, + ) + continue + + if "推流已彻底停止" in line and active: + if event_ts and int(active.get("duration_seconds") or 0) > 0: + active["ended_at"] = float(active["started_at"]) + int(active["duration_seconds"]) + elif event_ts: + active["ended_at"] = event_ts + sessions.append(_finalize_import_payload(active)) + active = None + closed += 1 + + if active: + sessions.append(_finalize_import_payload(active)) + + for payload in sessions: + if not payload.get("anchor_name"): + continue + if not payload.get("source_url"): + source_url, source_room_id = _resolve_anchor_url( + str(payload.get("anchor_name") or ""), + url_index, + url_lines, + log_url_index, + ) + payload["source_url"] = source_url + payload["source_room_id"] = source_room_id or payload.get("source_room_id") or "" + _persist_import_row( + conn, + payload, + started_at=float(payload["started_at"]), + ended_at=payload.get("ended_at"), + duration_seconds=int(payload.get("duration_seconds") or 0), + ) + imported += 1 + if youtube_key_suffix: + conn.execute( + f""" + UPDATE {_RELAY_SESSIONS_TABLE} + SET youtube_key_suffix = ?, updated_at = ? + WHERE process = ? AND COALESCE(youtube_key_suffix, '') = '' + """, + (youtube_key_suffix, time.time(), proc), + ) + conn.commit() + finally: + conn.close() + return { + "imported": imported, + "closed": closed, + "removed": removed, + "process": proc, + "log_path": str(path), + } + + +def _persist_import_close(conn, payload: dict[str, Any], ended_at: float) -> None: + started_at = float(payload.get("started_at") or ended_at) + duration = payload.get("duration_seconds") + if duration is None or int(duration) <= 0: + duration = int(max(0, ended_at - started_at)) + else: + ended_at = started_at + int(duration) + _persist_import_row(conn, payload, started_at=started_at, ended_at=ended_at, duration_seconds=int(duration)) + + +def _persist_import_open(conn, payload: dict[str, Any]) -> None: + started_at = float(payload.get("started_at") or time.time()) + duration = int(payload.get("duration_seconds") or 0) + _persist_import_row(conn, payload, started_at=started_at, ended_at=None, duration_seconds=duration) + + +def _persist_import_row( + conn, + payload: dict[str, Any], + *, + started_at: float, + ended_at: float | None, + duration_seconds: int, +) -> None: + anchor = str(payload.get("anchor_name") or "").strip() + stream_title = str(payload.get("stream_title") or "") + if not anchor and not stream_title: + return + if duration_seconds > 0 and started_at > 0: + computed_end = started_at + duration_seconds + if ended_at is None or ended_at < started_at: + ended_at = computed_end + dedupe_started = _timestamp_from_stream_title(stream_title) or started_at + existing = conn.execute( + f""" + SELECT id FROM {_RELAY_SESSIONS_TABLE} + WHERE process = ? AND anchor_name = ? AND stream_title = ? AND ABS(started_at - ?) < 180 + LIMIT 1 + """, + (payload.get("process") or "youtube", anchor, stream_title, dedupe_started), + ).fetchone() + if not existing and stream_title: + existing = conn.execute( + f""" + SELECT id FROM {_RELAY_SESSIONS_TABLE} + WHERE process = ? AND anchor_name = ? AND stream_title = ? + LIMIT 1 + """, + (payload.get("process") or "youtube", anchor, stream_title), + ).fetchone() + if existing: + return + now = time.time() + source_url = _clean_douyin_url(str(payload.get("source_url") or "")) + source_room_id = str(payload.get("source_room_id") or extract_source_room_id(source_url, stream_title, anchor)) + conn.execute( + f""" + INSERT INTO {_RELAY_SESSIONS_TABLE}( + session_uuid, process, channel_name, anchor_name, source_url, source_room_id, + stream_title, youtube_key_suffix, started_at, ended_at, duration_seconds, push_date, + cover_path, status, end_reason, metadata_json, created_at, updated_at + ) VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?, ?, '', ?, ?, ?, ?, ?) + """, + ( + str(uuid.uuid4()), + payload.get("process") or "youtube", + anchor, + source_url, + source_room_id, + stream_title, + str(payload.get("youtube_key_suffix") or ""), + started_at, + ended_at, + duration_seconds, + str(payload.get("push_date") or _push_date_from_ts(started_at)), + "ended" if ended_at else "active", + "imported_from_log", + _json_dumps({"imported": True, "stream_title": stream_title}), + now, + now, + ), + ) + + +def import_relay_sessions_for_process( + process: str, + *, + out_path: str | Path | None = None, + db_path: Path | None = None, + replace_imported: bool = False, + url_lines: str = "", +) -> dict[str, Any]: + proc = _normalize_process(process) + root = Path(os.environ.get("LIVE_PROJECT_ROOT") or Path(__file__).resolve().parent.parent) + loaded_url_lines, _youtube_ini_text, youtube_key_suffix = _load_process_config_texts(proc, root) + if not url_lines: + url_lines = loaded_url_lines + elif not youtube_key_suffix: + youtube_key_suffix = extract_youtube_key_suffix(_youtube_ini_text) + if out_path: + return import_relay_sessions_from_log( + out_path, + process=proc, + url_lines=url_lines, + youtube_key_suffix=youtube_key_suffix, + replace_imported=replace_imported, + db_path=db_path, + ) + candidates = [ + Path("/root/.pm2/logs") / f"{proc}-out.log", + Path(os.environ.get("PM2_HOME") or "") / "logs" / f"{proc}-out.log", + root / ".pm2" / "logs" / f"{proc}-out.log", + ] + for candidate in candidates: + if candidate.is_file() and candidate.stat().st_size > 0: + return import_relay_sessions_from_log( + candidate, + process=proc, + url_lines=url_lines, + youtube_key_suffix=youtube_key_suffix, + replace_imported=replace_imported, + db_path=db_path, + ) + return {"imported": 0, "closed": 0, "error": "pm2 log not found", "process": proc} diff --git a/d2ypp2/src/youtube_relay_slot.py b/d2ypp2/src/youtube_relay_slot.py new file mode 100644 index 0000000..d0c7381 --- /dev/null +++ b/d2ypp2/src/youtube_relay_slot.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +"""YouTube 单槽推流协调:与 youtube.py / douyin_youtube_ffplay 原有语义对齐。""" + +import threading +import time +from typing import Any + +from src.youtube_relay_heartbeat import clear_relay_heartbeat, read_relay_heartbeat, write_relay_heartbeat + +_slot_lock = threading.Lock() +_slot_owner: str | None = None +_CLAIM_GRACE_SECONDS = 15.0 + + +def _heartbeat_claim_fresh(hb: dict[str, Any]) -> bool: + if not hb: + return False + state = str(hb.get("state") or "").strip().lower() + if state not in {"claiming", "starting", "streaming", "source_failover"}: + return False + updated = float(hb.get("updated_at") or 0) + return updated > 0 and (time.time() - updated) <= _CLAIM_GRACE_SECONDS + 90.0 + + +def prune_orphan_relay_recording( + recording: set[str], + recording_time_list: dict[str, Any], + *, + pm2: str, + base_dir: str, +) -> None: + """仅清理孤儿占槽:recording 非空且无有效 relay heartbeat。""" + if not recording: + return + hb = read_relay_heartbeat(pm2, base_dir=base_dir) + if _heartbeat_claim_fresh(hb): + return + global _slot_owner + with _slot_lock: + recording.clear() + recording_time_list.clear() + _slot_owner = None + clear_relay_heartbeat(pm2, base_dir=base_dir) + + +def relay_slot_blocks(record_name: str, recording: set[str]) -> bool: + return any(name for name in recording if name and name != record_name) + + +def claim_relay_slot( + record_name: str, + *, + pm2: str, + base_dir: str, + anchor_name: str = "", +) -> bool: + global _slot_owner + with _slot_lock: + if _slot_owner is not None and _slot_owner != record_name: + return False + _slot_owner = record_name + write_relay_heartbeat( + pm2, + { + "state": "claiming", + "record_name": record_name, + "anchor_name": anchor_name, + "claimed_at": time.time(), + }, + base_dir=base_dir, + ) + return True + + +def release_relay_slot(record_name: str, *, pm2: str = "", base_dir: str = "") -> None: + global _slot_owner + with _slot_lock: + if _slot_owner == record_name: + _slot_owner = None + if pm2 and base_dir: + hb = read_relay_heartbeat(pm2, base_dir=base_dir) + if str(hb.get("record_name") or "") == record_name: + clear_relay_heartbeat(pm2, base_dir=base_dir) + + +def _flv_is_h265(url: str) -> bool: + lower = (url or "").lower() + if "codec=h265" in lower or "codec=hevc" in lower: + return True + try: + from src import utils + + codec = utils.get_query_params(url, "codec") + if codec and str(codec[0]).lower() in {"h265", "hevc"}: + return True + except Exception: + pass + return False + + +def youtube_stream_fallback_urls(port_info: dict[str, Any], primary: str) -> list[str]: + primary_text = (primary or "").strip() + out: list[str] = [] + seen: set[str] = set() + for key in ("flv_url", "m3u8_url"): + url = str(port_info.get(key) or "").strip() + if not url or url == primary_text or url in seen: + continue + if not url.startswith("http"): + continue + if key == "flv_url" and _flv_is_h265(url): + continue + seen.add(url) + out.append(url) + return out diff --git a/d2ypp2/tests/test_neko_config.py b/d2ypp2/tests/test_neko_config.py index 721e5ec..48f7699 100644 --- a/d2ypp2/tests/test_neko_config.py +++ b/d2ypp2/tests/test_neko_config.py @@ -231,6 +231,8 @@ class NekoConfigTests(unittest.TestCase): "chown_neko_profile_tree()", "neko_profile_owner()", "resolve_neko_browser_proxy()", + "resolve_neko_nat1to1()", + "neko_shellcrash_proxy_port_from_url()", "neko_browser_proxy_auto_enable_if_needed", "stack_env_upsert", "neko_browser_proxy_switch_enabled()", @@ -285,6 +287,7 @@ class NekoConfigTests(unittest.TestCase): "service_neko_restart()", "service_neko_reconfigure", "service_neko_reconfigure_for_shellcrash_change", + "stack_env_upsert NEKO_BROWSER_PROXY", "ENABLE_NEKO_BROWSER_PROXY", "neko_http_probe_code()", "published=", @@ -506,6 +509,36 @@ class NekoConfigTests(unittest.TestCase): self.assertIn('NEKO_DESKTOP_SCREEN="${NEKO_DESKTOP_SCREEN:-1280x720@15}"', service_ctl) self.assertNotIn('NEKO_DESKTOP_SCREEN="${NEKO_DESKTOP_SCREEN:-1920x1080@30}"', common) + def test_neko_ip_watcher_uses_resolve_neko_nat1to1(self) -> None: + watcher = (ROOT / "scripts" / "linux" / "neko_ip_watch.sh").read_text(encoding="utf-8") + self.assertIn("resolve_neko_nat1to1", watcher) + self.assertNotIn('target="${NEKO_WEBRTC_NAT1TO1:-}"', watcher) + + def test_resolve_neko_nat1to1_prefers_wireguard_in_remote_mode(self) -> None: + script = ( + f"ROOT_DIR={ROOT!s}; " + f"source {ROOT / 'scripts' / 'linux' / 'lib' / 'common.sh'}; " + "ip() { " + " if [ \"$1\" = -4 ] && [ \"$2\" = addr ] && [ \"$3\" = show ]; then " + " printf '%s\\n' '1: lo inet 127.0.0.1'; " + " printf '%s\\n' '3: enp2s0 inet 192.168.21.73'; " + " printf '%s\\n' '5: wgeasy inet 10.88.0.5'; " + " return 0; " + " fi; " + " command ip \"$@\"; " + "}; " + "detect_preferred_lan_ip() { printf '%s\\n' 192.168.21.73; }; " + "NEKO_ACCESS_MODE=remote; " + "NEKO_WIREGUARD_HOST=10.88.0.5; " + "NEKO_WEBRTC_NAT1TO1=192.168.21.73; " + "resolve_neko_nat1to1" + ) + proc = subprocess.run(["bash", "-lc", script], capture_output=True, text=True, check=False) + if proc.returncode != 0 and bash_unavailable(proc): + self.skipTest("bash is unavailable in this Windows environment") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout.strip(), "10.88.0.5") + def test_neko_ip_watcher_is_installed_and_restarts_on_drift(self) -> None: common = (ROOT / "scripts" / "linux" / "lib" / "common.sh").read_text(encoding="utf-8") watcher = (ROOT / "scripts" / "linux" / "neko_ip_watch.sh").read_text(encoding="utf-8") diff --git a/d2ypp2/tests/test_youtube_relay_log.py b/d2ypp2/tests/test_youtube_relay_log.py new file mode 100644 index 0000000..ddfb1e7 --- /dev/null +++ b/d2ypp2/tests/test_youtube_relay_log.py @@ -0,0 +1,185 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from src.youtube_relay_log import ( + close_active_relay_sessions, + end_relay_session, + import_relay_sessions_from_log, + list_relay_sessions, + on_relay_push_start, + start_relay_session, + sync_relay_from_recent_log, +) + + +class YoutubeRelayLogTests(unittest.TestCase): + def test_start_and_end_session(self) -> None: + with tempfile.TemporaryDirectory() as td: + db = Path(td) / "hub_state.sqlite" + started = start_relay_session( + process="youtube", + anchor_name="又系_柠檬茶", + source_url="https://live.douyin.com/745277409780", + source_room_id="745277409780", + stream_title="又系_柠檬茶_2026-06-24_03-59-00", + channel_name="线路1", + db_path=db, + ) + self.assertEqual(started["anchor_name"], "又系_柠檬茶") + self.assertEqual(started["source_room_id"], "745277409780") + self.assertEqual(started["status"], "active") + self.assertEqual(started["push_date"], "2026-06-24") + + ended = end_relay_session("youtube", anchor_name="又系_柠檬茶", reason="push_stopped", db_path=db) + assert ended is not None + self.assertEqual(ended["status"], "ended") + self.assertIsNotNone(ended["ended_at"]) + self.assertGreaterEqual(ended["duration_seconds"], 0) + + def test_on_relay_push_start_dedupes_same_anchor(self) -> None: + with tempfile.TemporaryDirectory() as td: + db = Path(td) / "hub_state.sqlite" + first = on_relay_push_start( + process="youtube", + anchor_name="樱桃炒饭(摆摊版)", + record_url="https://live.douyin.com/334176667239", + stream_title="樱桃炒饭(摆摊版)_2026-06-24_07-10-00", + real_url="https://pull-flv.example/live.flv", + db_path=db, + ) + second = on_relay_push_start( + process="youtube", + anchor_name="樱桃炒饭(摆摊版)", + record_url="https://live.douyin.com/334176667239", + stream_title="樱桃炒饭(摆摊版)_2026-06-24_07-10-00", + real_url="https://pull-flv.example/live.flv", + db_path=db, + ) + self.assertEqual(first["id"], second["id"]) + listing = list_relay_sessions(process="youtube", db_path=db) + self.assertEqual(listing["total"], 1) + + def test_source_switch_closes_previous_session(self) -> None: + with tempfile.TemporaryDirectory() as td: + db = Path(td) / "hub_state.sqlite" + first = start_relay_session( + process="youtube", + anchor_name="主播A", + source_url="https://live.douyin.com/111", + db_path=db, + ) + second = start_relay_session( + process="youtube", + anchor_name="主播B", + source_url="https://live.douyin.com/222", + db_path=db, + ) + self.assertNotEqual(first["id"], second["id"]) + listing = list_relay_sessions(process="youtube", status="ended", db_path=db) + self.assertEqual(listing["total"], 1) + active = list_relay_sessions(process="youtube", status="active", db_path=db) + self.assertEqual(active["total"], 1) + self.assertEqual(active["sessions"][0]["anchor_name"], "主播B") + + def test_list_relay_sessions_search_and_date_filter(self) -> None: + with tempfile.TemporaryDirectory() as td: + db = Path(td) / "hub_state.sqlite" + start_relay_session( + process="youtube", + anchor_name="音乐主播", + source_url="https://live.douyin.com/99887766", + source_room_id="99887766", + stream_title="音乐主播_2026-06-20_12-00-00", + db_path=db, + ) + start_relay_session( + process="youtube2__lane1", + anchor_name="其他主播", + source_url="https://live.douyin.com/11223344", + db_path=db, + ) + + by_q = list_relay_sessions(q="99887766", db_path=db) + self.assertEqual(by_q["total"], 1) + self.assertEqual(by_q["sessions"][0]["anchor_name"], "音乐主播") + + by_proc = list_relay_sessions(process="youtube2__lane1", db_path=db) + self.assertEqual(by_proc["total"], 1) + + def test_sync_relay_from_recent_log(self) -> None: + with tempfile.TemporaryDirectory() as td: + db = Path(td) / "hub_state.sqlite" + recent_log = "\n".join( + [ + "2026-06-24T06:04:11: INFO | 06:04:11 | 正在录制 1 个: 又系_柠檬茶[原画 2:05:11]", + ] + ) + url_lines = "https://live.douyin.com/745277409780 又系_柠檬茶\n" + synced = sync_relay_from_recent_log( + "youtube", + recent_log, + channel_name="线路1", + url_lines=url_lines, + db_path=db, + ) + assert synced is not None + self.assertEqual(synced["anchor_name"], "又系_柠檬茶") + self.assertIn("745277409780", synced["source_url"]) + self.assertEqual(synced["duration_seconds"], 2 * 3600 + 5 * 60 + 11) + + def test_import_relay_sessions_from_log(self) -> None: + with tempfile.TemporaryDirectory() as td: + db = Path(td) / "hub_state.sqlite" + log_path = Path(td) / "youtube-out.log" + log_path.write_text( + "\n".join( + [ + "2026-06-24T08:59:10: [INFO] 又系_柠檬茶 准备开始录制视频: /opt/live/d2ypp/downloads/抖音直播/又系_柠檬茶 开始推流到 YouTube: 又系_柠檬茶_2026-06-24_03-59-10", + "2026-06-24T11:04:11: 监测 29 | 并发 3 | 代理 开 | 错误 0 | 06:04:11 | 正在录制 1 个: 又系_柠檬茶[原画 2:05:01]", + "2026-06-24T11:05:00: [INFO] 推流已彻底停止并清理完毕", + "2026-06-24T12:10:00: [INFO] 樱桃炒饭(摆摊版) 开始推流到 YouTube: 樱桃炒饭(摆摊版)_2026-06-24_07-10-00", + "2026-06-24T14:15:30: 监测 29 | 并发 3 | 代理 开 | 错误 0 | 09:15:30 | 正在录制 1 个: 樱桃炒饭(摆摊版)[原画 2:05:30]", + ] + ), + encoding="utf-8", + ) + url_lines = "\n".join( + [ + "https://live.douyin.com/745277409780,主播: 又系_柠檬茶", + "https://live.douyin.com/334176667239,主播: 樱桃炒饭(摆摊版)", + ] + ) + result = import_relay_sessions_from_log( + log_path, + process="youtube", + url_lines=url_lines, + youtube_key_suffix="h-ijkl", + replace_imported=True, + db_path=db, + ) + self.assertGreaterEqual(result["imported"], 1) + listing = list_relay_sessions(process="youtube", db_path=db) + anchors = {row["anchor_name"] for row in listing["sessions"]} + self.assertIn("又系_柠檬茶", anchors) + self.assertIn("樱桃炒饭(摆摊版)", anchors) + lemon = next(row for row in listing["sessions"] if row["anchor_name"] == "又系_柠檬茶") + self.assertIn("745277409780", lemon["source_url"]) + self.assertGreaterEqual(lemon["duration_seconds"], 2 * 3600 + 5 * 60) + self.assertEqual(lemon["youtube_key_suffix"], "h-ijkl") + + def test_close_active_relay_sessions(self) -> None: + with tempfile.TemporaryDirectory() as td: + db = Path(td) / "hub_state.sqlite" + start_relay_session(process="youtube", anchor_name="待关闭", db_path=db) + closed = close_active_relay_sessions("youtube", reason="restart", db_path=db) + self.assertEqual(len(closed), 1) + self.assertEqual(closed[0]["end_reason"], "restart") + active = list_relay_sessions(process="youtube", status="active", db_path=db) + self.assertEqual(active["total"], 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/d2ypp2/tests/test_youtube_relay_slot.py b/d2ypp2/tests/test_youtube_relay_slot.py new file mode 100644 index 0000000..944734c --- /dev/null +++ b/d2ypp2/tests/test_youtube_relay_slot.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import time +import unittest +from unittest.mock import patch + +from src.youtube_relay_slot import ( + claim_relay_slot, + prune_orphan_relay_recording, + relay_slot_blocks, + release_relay_slot, + youtube_stream_fallback_urls, +) + + +class YoutubeRelaySlotTests(unittest.TestCase): + def setUp(self) -> None: + release_relay_slot("序号1 主播A") + release_relay_slot("序号2 主播B") + + def test_relay_slot_blocks_other_channel_only(self) -> None: + recording = {"序号1 主播A"} + self.assertTrue(relay_slot_blocks("序号2 主播B", recording)) + self.assertFalse(relay_slot_blocks("序号1 主播A", recording)) + + def test_prune_only_when_recording_without_heartbeat(self) -> None: + recording = {"序号1 主播A"} + times = {"序号1 主播A": ["now", "原画"]} + with patch("src.youtube_relay_slot.read_relay_heartbeat", return_value={}): + prune_orphan_relay_recording( + recording, + times, + pm2="youtube2__lane1", + base_dir="/tmp", + ) + self.assertEqual(recording, set()) + self.assertEqual(times, {}) + + def test_prune_keeps_slot_when_heartbeat_exists(self) -> None: + recording = {"序号1 主播A"} + times = {"序号1 主播A": ["now", "原画"]} + with patch( + "src.youtube_relay_slot.read_relay_heartbeat", + return_value={"state": "streaming", "updated_at": time.time()}, + ): + prune_orphan_relay_recording( + recording, + times, + pm2="youtube2__lane1", + base_dir="/tmp", + ) + self.assertEqual(recording, {"序号1 主播A"}) + + def test_claim_and_release_slot(self) -> None: + with patch("src.youtube_relay_slot.write_relay_heartbeat"): + self.assertTrue( + claim_relay_slot("序号1 主播A", pm2="youtube2__lane1", base_dir="/tmp"), + ) + self.assertFalse( + claim_relay_slot("序号2 主播B", pm2="youtube2__lane1", base_dir="/tmp"), + ) + release_relay_slot("序号1 主播A", pm2="youtube2__lane1", base_dir="/tmp") + self.assertTrue( + claim_relay_slot("序号2 主播B", pm2="youtube2__lane1", base_dir="/tmp"), + ) + + def test_stream_fallback_urls_same_room_only(self) -> None: + urls = youtube_stream_fallback_urls( + { + "flv_url": "http://pull-flv.example.com/a.flv", + "m3u8_url": "http://pull-hls.example.com/a.m3u8", + "record_url": "https://live.douyin.com/123", + }, + "http://pull-flv.example.com/a.flv", + ) + self.assertEqual(urls, ["http://pull-hls.example.com/a.m3u8"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/d2ypp2/tools/analyze_host03_room_sessions.py b/d2ypp2/tools/analyze_host03_room_sessions.py new file mode 100644 index 0000000..6a79b84 --- /dev/null +++ b/d2ypp2/tools/analyze_host03_room_sessions.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +import paramiko, sys, base64, re + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +REMOTE = r''' +import re +path = "/root/.pm2/logs/youtube-out.log" +with open(path, "r", errors="replace") as f: + lines = f.readlines() + +def parse(ln): + if "正在录制 1" not in ln or "[原画" not in ln: + return None + try: + after = ln.split("正在录制 1", 1)[1] + name = after.split("[原画", 1)[0].strip(" :?") + dur = after.split("[原画", 1)[1].split("]", 1)[0].strip() + parts = ln.split("|") + local_t = parts[-2].strip() + if not re.match(r"\d{2}:\d{2}:\d{2}", local_t): + return None + return local_t, name, dur + except Exception: + return None + +targets = ["又系", "樱桃", "钟楼", "橙堡", "伟利", "李泽宇", "小翻翻"] +for target in targets: + first=None; last=None; hit205=None + for ln in lines: + if '2026-06-24' not in ln: continue + p=parse(ln) + if not p: continue + lt,name,dur=p + if target not in name: continue + if first is None: first=(lt,dur,name) + last=(lt,dur,name) + if hit205 is None and dur.startswith('2:05'): + hit205=(lt,dur,name) + print('\nTARGET', target) + print(' first', first) + print(' 2:05 ', hit205) + print(' last ', last) + +# detect switches by first 0:00:xx duration +print('\n=== session starts (dur < 0:02:00) ===') +for ln in lines: + if '2026-06-24' not in ln: continue + p=parse(ln) + if not p: continue + lt,name,dur=p + if dur.startswith('0:00') or dur.startswith('0:01'): + if any(t in name for t in targets): + print(lt, dur, name) +''' +b64 = base64.b64encode(REMOTE.encode()).decode() +cmd = f"echo {PASS} | sudo -S python3 -c \"import base64; exec(base64.b64decode('{b64}').decode())\"" +c = paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect(HOST, username=USER, password=PASS, timeout=15) +_, o, e = c.exec_command(cmd, timeout=180, get_pty=True) +out = (o.read() + e.read()).decode("utf-8", "replace") +c.close() +sys.stdout.buffer.write(out.encode("utf-8", "replace")) diff --git a/d2ypp2/tools/analyze_host03_youtube_log.py b/d2ypp2/tools/analyze_host03_youtube_log.py new file mode 100644 index 0000000..bde4fd4 --- /dev/null +++ b/d2ypp2/tools/analyze_host03_youtube_log.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +import paramiko, sys, base64, re + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +REMOTE = r''' +import re +path = "/root/.pm2/logs/youtube-out.log" +with open(path, "r", errors="replace") as f: + lines = f.readlines() + +pat = re.compile(r"正在录制 1 .: ([^\[]+)\[原画 ([0-9:]+)\].*\| (\d{2}:\d{2}:\d{2}) \|") +# fallback: split-based parser +def parse(ln): + if "正在录制 1" not in ln or "[原画" not in ln: + return None + try: + after = ln.split("正在录制 1", 1)[1] + name = after.split("[原画", 1)[0].strip(" :?") + dur = after.split("[原画", 1)[1].split("]", 1)[0].strip() + parts = ln.split("|") + local_t = parts[-2].strip() if len(parts) >= 2 else "" + if not re.match(r"\d{2}:\d{2}:\d{2}", local_t): + return None + return local_t, name, dur, ln.strip()[:220] + except Exception: + return None + +# local time 07:00-07:30 on Jun24 session (any log date) +print('=== local 07:00-07:30 recordings ===') +rows=[] +for ln in lines: + if '2026-06-24' not in ln and '2026-06-25' not in ln: + continue + p=parse(ln) + if not p: continue + lt,name,dur,_=p + h,m,s=map(int,lt.split(':')) + if h==7 and m<30: + rows.append((lt,dur,name)) +for r in rows[::15][:40]: + print(r) + +# first time each room hits >=2:05:00 today +print('\n=== first >=2:05:00 per room (local time) ===') +seen={} +for ln in lines: + if '2026-06-24' not in ln: continue + p=parse(ln) + if not p: continue + lt,name,dur,_=p + parts=dur.split(':') + if len(parts)==3: + sec=int(parts[0])*3600+int(parts[1])*60+int(parts[2]) + elif len(parts)==2: + sec=int(parts[0])*60+int(parts[1]) + else: + continue + if sec >= 2*3600+5*60 and name not in seen: + seen[name]=(lt,dur,ln.strip()[:200]) +for name,v in seen.items(): + print(v[0], v[1], name) + +# around 12h before 19:20 => 07:20, find closest 2:05 duration line +print('\n=== lines with duration 2:04-2:06 and local 06:30-08:00 ===') +for ln in lines: + if '2026-06-24' not in ln: continue + p=parse(ln) + if not p: continue + lt,name,dur,_=p + if not re.match(r'2:0[4-6]:', dur): + continue + h=int(lt.split(':')[0]) + if 6 <= h <= 8: + print(lt, dur, name) + +# what was recording at local 07:10 exactly (nearest lines) +print('\n=== nearest to local 07:10 ===') +best=[] +for ln in lines: + if '2026-06-24' not in ln: continue + p=parse(ln) + if not p: continue + lt,name,dur,_=p + h,m,s=map(int,lt.split(':')) + if h==7 and 8<=m<=12: + best.append((lt,dur,name)) +for r in best[::3]: + print(r) + +# room switches: 准备开始录制 +print('\n=== start recording events local 05:00-08:30 ===') +for ln in lines: + if '准备开始录制' not in ln and '开始推流到 YouTube' not in ln: + continue + if '2026-06-24' not in ln: continue + # extract anchor from line + if '2026-06-24T1' in ln or '2026-06-24T0' in ln or '2026-06-25T0' in ln: + print(ln.strip()[:240]) +''' +b64 = base64.b64encode(REMOTE.encode()).decode() +cmd = f"echo {PASS} | sudo -S python3 -c \"import base64; exec(base64.b64decode('{b64}').decode())\"" +c = paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect(HOST, username=USER, password=PASS, timeout=15) +_, o, e = c.exec_command(cmd, timeout=180, get_pty=True) +out = (o.read() + e.read()).decode("utf-8", "replace") +c.close() +sys.stdout.buffer.write(out.encode("utf-8", "replace")) diff --git a/d2ypp2/tools/check_host03_deploy.py b/d2ypp2/tools/check_host03_deploy.py new file mode 100644 index 0000000..a082bf8 --- /dev/null +++ b/d2ypp2/tools/check_host03_deploy.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""Check what JS is actually served on host03 for live_youtube.""" +from __future__ import annotations + +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +BASE = "/opt/live/d2ypp" + +cmds = [ + f"grep -r 'hideStatusOverview' {BASE}/web-console/out {BASE}/web-console/components 2>/dev/null | head -5", + f"grep -r 'HIDE_YOUTUBE_LIVE_PROCESS_LOG' {BASE}/web-console 2>/dev/null | head -5", + f"grep -r '进程状态' {BASE}/web-console/out/_next 2>/dev/null | head -3", + f"ls -la {BASE}/web-console/out/index.html {BASE}/web-console/out/_next/static/chunks/app/page*.js 2>/dev/null", + "curl -sS http://127.0.0.1:8001/ | head -c 2000", + f"stat {BASE}/web-console/out/index.html 2>/dev/null", + f"grep 'hideStatusOverview' {BASE}/web-console/out/_next/static/chunks/*.js 2>/dev/null | head -2", + f"find {BASE}/web-console/out/_next/static/chunks -name 'page*.js' -printf '%T@ %p\\n' 2>/dev/null | sort -nr | head -5", +] + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect(HOST, username=USER, password=PASS, timeout=20) +for cmd in cmds: + _, o, e = c.exec_command(cmd, timeout=60) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(f"\n=== {cmd[:90]} ===\n{out[:2500]}") +c.close() diff --git a/d2ypp2/tools/check_relay_slot_hosts.py b/d2ypp2/tools/check_relay_slot_hosts.py new file mode 100644 index 0000000..223f661 --- /dev/null +++ b/d2ypp2/tools/check_relay_slot_hosts.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Check relay-slot bug presence on host03 and host05.""" +from __future__ import annotations + +import json +import paramiko +import sys + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOSTS = [ + ("10.88.0.3", "eric", "Xiao4669805", "/opt/live/d2ypp"), + ("10.88.0.5", "eric", "4669805", "/home/eric/d2ypp2-src"), +] + + +def run(ssh, cmd, timeout=90): + _, o, e = ssh.exec_command(cmd, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace").strip() + + +def check_host(host, user, pw, base): + print(f"\n{'='*72}\n{host} base={base}\n{'='*72}") + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + try: + ssh.connect(host, username=user, password=pw, timeout=25) + except Exception as exc: + print(f"SSH FAIL: {exc}") + return + + print("health:", run(ssh, "curl -sf -m 5 http://127.0.0.1:8001/health || echo FAIL")) + + # --- code markers --- + markers = { + "old_len_recording_guard": run( + ssh, f"grep -n 'len(recording) > 0' {base}/youtube.py 2>/dev/null | head -3 || echo absent" + ), + "new_relay_slot_import": run( + ssh, + f"grep -n 'youtube_relay_slot' {base}/youtube.py 2>/dev/null | head -3 || echo absent", + ), + "relay_slot_module": run( + ssh, f"test -f {base}/src/youtube_relay_slot.py && echo present || echo missing" + ), + "wrong_fallback_urls": run( + ssh, + f"grep -n 'url_line_list' {base}/youtube.py 2>/dev/null | grep fallback || echo absent", + ), + "stream_input_filter": run( + ssh, + f"grep -n '_is_probable_stream_input' {base}/douyin_youtube_ffplay.py 2>/dev/null | head -1 || echo absent", + ), + "hub_is_file_fix": run( + ssh, + f"grep -n 'url_file = Path' {base}/src/hub_routes.py 2>/dev/null | head -1 || echo absent", + ), + } + print("\n--- code markers ---") + for k, v in markers.items(): + print(f"{k}: {v}") + + has_old_bug = "len(recording) > 0" in markers["old_len_recording_guard"] + has_fix = ( + markers["relay_slot_module"] == "present" + and "absent" not in markers["new_relay_slot_import"] + and "absent" not in markers["stream_input_filter"] + ) + print(f"\nBUG STATUS: old_guard={has_old_bug} fix_deployed={has_fix}") + + # --- youtube processes --- + print("\n--- youtube processes ---") + print(run(ssh, "ps aux | grep -E 'python.*youtube\\.py' | grep -v grep | head -5 || echo none")) + + # --- pm2 / local registry --- + print("\n--- process list (api) ---") + try: + dash = json.loads(run(ssh, "curl -sS -m 15 http://127.0.0.1:8001/hub/dashboard")) + yt_procs = [ + p + for p in dash.get("live", {}).get("processes", []) + if "youtube" in str(p.get("pm2", "")).lower() + ] + for p in yt_procs[:6]: + print( + f" {p.get('pm2')}: status={p.get('process_status')} " + f"biz={p.get('business_status')} pushing={p.get('is_pushing')} " + f"note={(p.get('business_note') or '')[:80]}" + ) + if len(yt_procs) > 6: + print(f" ... +{len(yt_procs)-6} more") + except Exception as exc: + print(f"dashboard parse fail: {exc}") + + # --- ffmpeg --- + print("\n--- ffmpeg rtmps ---") + print(run(ssh, "pgrep -af 'ffmpeg.*rtmps' | grep -v pgrep | head -3 || echo none")) + + # --- find active youtube log --- + log_dir = f"{base}/.pm2/logs" + logs = run(ssh, f"ls -t {log_dir}/youtube2__*-out.log 2>/dev/null | head -5") + active_log = "" + for lg in logs.splitlines(): + if not lg.strip(): + continue + tail = run(ssh, f"tail -3 {lg}") + if "正在录制" in tail or "启动 YouTube" in tail or "正在直播中" in tail: + active_log = lg.strip() + break + if not active_log and logs.splitlines(): + active_log = logs.splitlines()[0].strip() + + if active_log: + print(f"\n--- log tail: {active_log.split('/')[-1]} ---") + print(run(ssh, f"tail -25 {active_log}")[-2500:]) + + print("\n--- log patterns (stuck live + blocked) ---") + patterns = run( + ssh, + f"grep -E '正在直播中|正在录制|启动 YouTube|推流已彻底停止|切换备用源|跳过非直链|len\\(recording\\)' " + f"{active_log} 2>/dev/null | tail -15", + ) + print(patterns[-2000:] if patterns else "(no matches)") + + # check wrong fallback in recent log + wrong_fb = run( + ssh, + f"grep -E '切换备用源 URL.*live\\.douyin\\.com' {active_log} 2>/dev/null | tail -5", + ) + if wrong_fb: + print("\n--- WRONG FALLBACK (page URL as ffmpeg input) ---") + print(wrong_fb) + + # --- is_file dashboard error --- + err_is_file = run( + ssh, + "curl -sS -m 12 http://127.0.0.1:8001/hub/dashboard | " + "python3 -c \"import sys,json; d=json.load(sys.stdin); " + "print([p.get('business_note') for p in d.get('live',{}).get('processes',[]) " + "if 'is_file' in str(p.get('business_note',''))][:3])\" 2>/dev/null || echo check_failed", + ) + print(f"\n--- dashboard is_file errors: {err_is_file} ---") + + ssh.close() + + +for h, u, p, b in HOSTS: + check_host(h, u, p, b) diff --git a/d2ypp2/tools/debug_host03_web_import.py b/d2ypp2/tools/debug_host03_web_import.py new file mode 100644 index 0000000..173c203 --- /dev/null +++ b/d2ypp2/tools/debug_host03_web_import.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import sys +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +BASE = "/opt/live/d2ypp" + + +def run(cmd: str, timeout: int = 120) -> str: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=20) + _, o, e = c.exec_command("export LC_ALL=C.UTF-8 LANG=C.UTF-8; " + cmd, timeout=timeout) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +def safe_print(text: str) -> None: + try: + print(text) + except UnicodeEncodeError: + sys.stdout.buffer.write(text.encode("utf-8", errors="replace") + b"\n") + + +cmds = [ + f"journalctl -u live-console.service -n 60 --no-pager 2>&1 | tail -40", + f"cd {BASE} && .venv/bin/python -c \"import web; print('web_import_ok')\" 2>&1", + f"cd {BASE} && .venv/bin/python -c \"from src.youtube_relay_log import list_relay_sessions; print(list_relay_sessions(limit=1))\" 2>&1", +] +for cmd in cmds: + safe_print(f"\n=== {cmd[:80]} ===\n{run(cmd)[:4000]}") diff --git a/d2ypp2/tools/deploy_neko_nat1to1_fix_host04.py b/d2ypp2/tools/deploy_neko_nat1to1_fix_host04.py new file mode 100644 index 0000000..b6a3289 --- /dev/null +++ b/d2ypp2/tools/deploy_neko_nat1to1_fix_host04.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Fix NEKO_WEBRTC_NAT1TO1 on 10.88.0.4 for WireGuard WebRTC access.""" +from __future__ import annotations + +import re +import time +from pathlib import Path + +import paramiko + +HOST, USER, PASS = "10.88.0.4", "eric", "4669805" +REMOTE_BASE = "/home/eric/d2ypp2-src" +ROOT = Path(__file__).resolve().parent.parent +FILES = [ + "scripts/linux/service_ctl.sh", + "scripts/linux/lib/common.sh", + "scripts/linux/neko_ip_watch.sh", +] + + +def run(c: paramiko.SSHClient, cmd: str, timeout: int = 300) -> str: + _, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def sudo(c: paramiko.SSHClient, cmd: str, timeout: int = 300) -> str: + return run(c, f"echo {PASS!r} | sudo -S -p '' bash -lc {cmd!r}", timeout=timeout) + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=20) + + sftp = c.open_sftp() + stamp = int(time.time()) + for rel in FILES: + local = ROOT / rel + remote_tmp = f"/tmp/{Path(rel).name}.{stamp}" + sftp.put(str(local), remote_tmp) + sudo(c, f"cp {remote_tmp} {REMOTE_BASE}/{rel} && chmod +x {REMOTE_BASE}/{rel}") + print(f"uploaded {rel}") + sftp.close() + + env_path = f"{REMOTE_BASE}/config/system-stack.env" + raw = run(c, f"cat {env_path}") + for key, val in [ + ("NEKO_WEBRTC_NAT1TO1", "10.88.0.4"), + ("NEKO_WIREGUARD_HOST", "10.88.0.4"), + ("NEKO_ACCESS_MODE", "remote"), + ]: + if re.search(rf"^{re.escape(key)}=", raw, re.M): + raw = re.sub(rf"^{re.escape(key)}=.*$", f"{key}={val}", raw, count=1, flags=re.M) + else: + raw = raw.rstrip() + f"\n{key}={val}\n" + + tmp_env = f"/tmp/system-stack.env.{stamp}" + sftp = c.open_sftp() + with sftp.file(tmp_env, "w") as fh: + fh.write(raw.replace("\r\n", "\n").replace("\r", "\n")) + sftp.close() + sudo(c, f"cp {tmp_env} {env_path}") + print("env:", run(c, f"grep -E 'NEKO_ACCESS_MODE|NEKO_WIREGUARD_HOST|NEKO_WEBRTC_NAT1TO1' {env_path}")) + + print( + sudo( + c, + f"docker rm -f live-neko-1 live-neko-2 2>/dev/null || true; " + f"bash {REMOTE_BASE}/scripts/linux/service_ctl.sh neko start; " + f"bash {REMOTE_BASE}/scripts/linux/service_ctl.sh neko status | head -30", + timeout=600, + ) + ) + print(sudo(c, "systemctl restart live-neko-ip-watch.service")) + time.sleep(10) + print(run(c, "curl -sS -m 5 -o /dev/null -w 'local9200=%{http_code}\n' http://127.0.0.1:9200/")) + print(run(c, "curl -sS -m 5 -o /dev/null -w 'wg9200=%{http_code}\n' http://10.88.0.4:9200/")) + print(sudo(c, "docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' | grep neko || true")) + print( + sudo( + c, + "docker inspect live-neko-1 --format '{{range .Config.Env}}{{println .}}{{end}}' | grep NEKO_WEBRTC_NAT1TO1 || true", + ) + ) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/deploy_neko_nat1to1_fix_host05.py b/d2ypp2/tools/deploy_neko_nat1to1_fix_host05.py new file mode 100644 index 0000000..60b17b0 --- /dev/null +++ b/d2ypp2/tools/deploy_neko_nat1to1_fix_host05.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import re +import time +from pathlib import Path + +import paramiko + +HOST, USER, PASS = "10.88.0.5", "eric", "4669805" +REMOTE_BASE = "/opt/live/d2ypp" +ROOT = Path(__file__).resolve().parent.parent +FILES = [ + "scripts/linux/service_ctl.sh", + "scripts/linux/lib/common.sh", + "scripts/linux/neko_ip_watch.sh", +] + + +def run(c: paramiko.SSHClient, cmd: str, timeout: int = 300) -> str: + _, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def sudo(c: paramiko.SSHClient, cmd: str, timeout: int = 300) -> str: + return run(c, f"echo {PASS!r} | sudo -S -p '' bash -lc {cmd!r}", timeout=timeout) + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=20) + + sftp = c.open_sftp() + stamp = int(time.time()) + for rel in FILES: + local = ROOT / rel + remote_tmp = f"/tmp/{Path(rel).name}.{stamp}" + sftp.put(str(local), remote_tmp) + sudo(c, f"cp {remote_tmp} {REMOTE_BASE}/{rel} && chmod +x {REMOTE_BASE}/{rel}") + print(f"uploaded {rel}") + sftp.close() + + env_path = f"{REMOTE_BASE}/config/system-stack.env" + raw = run(c, f"cat {env_path}") + if re.search(r"^NEKO_WEBRTC_NAT1TO1=", raw, re.M): + new_raw = re.sub(r"^NEKO_WEBRTC_NAT1TO1=.*$", "NEKO_WEBRTC_NAT1TO1=10.88.0.5", raw, count=1, flags=re.M) + else: + new_raw = raw.rstrip() + "\nNEKO_WEBRTC_NAT1TO1=10.88.0.5\n" + tmp_env = f"/tmp/system-stack.env.{stamp}" + sftp = c.open_sftp() + with sftp.file(tmp_env, "w") as fh: + fh.write(new_raw) + sftp.close() + sudo(c, f"cp {tmp_env} {env_path}") + print("env:", run(c, f"grep -E 'NEKO_ACCESS_MODE|NEKO_WIREGUARD_HOST|NEKO_WEBRTC_NAT1TO1' {env_path}")) + + print( + sudo( + c, + f"docker rm -f live-neko-1 live-neko-2 2>/dev/null || true; " + f"bash {REMOTE_BASE}/scripts/linux/service_ctl.sh neko start; " + f"bash {REMOTE_BASE}/scripts/linux/service_ctl.sh neko status | head -25", + timeout=600, + ) + ) + print(sudo(c, "systemctl restart live-neko-ip-watch.service")) + time.sleep(8) + print(run(c, "curl -sS -m 5 -o /dev/null -w 'local9200=%{http_code}\n' http://127.0.0.1:9200/")) + print(run(c, "curl -sS -m 5 -o /dev/null -w 'wg9200=%{http_code}\n' http://10.88.0.5:9200/")) + print(sudo(c, "docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' | grep neko || true")) + print( + sudo( + c, + "docker inspect live-neko-1 --format '{{range .Config.Env}}{{println .}}{{end}}' | grep NEKO_WEBRTC_NAT1TO1 || true", + ) + ) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/deploy_relay_fix_all_hosts.py b/d2ypp2/tools/deploy_relay_fix_all_hosts.py new file mode 100644 index 0000000..f8affd6 --- /dev/null +++ b/d2ypp2/tools/deploy_relay_fix_all_hosts.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Deploy relay-slot + UI fixes to 3 hosts; restart live-console and non-pushing youtube lanes.""" +from __future__ import annotations + +import io +import json +import paramiko +import tarfile +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +BACKEND_FILES = [ + "src/youtube_relay_slot.py", + "youtube.py", + "douyin_youtube_ffplay.py", + "src/hub_routes.py", +] + +HOSTS = [ + ("192.168.2.237", "eric", "4669805", "/home/eric/d2ypp2-src"), + ("10.88.0.3", "eric", "Xiao4669805", "/opt/live/d2ypp"), + ("10.88.0.5", "eric", "4669805", "/opt/live/d2ypp"), +] + +CONSOLE_OUT = ROOT / "web-console" / "out" + + +def put_lf(sftp, local: Path, remote: str) -> None: + data = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + sftp.putfo(io.BytesIO(data), remote) + + +def run(ssh, cmd, timeout=180): + _, o, e = ssh.exec_command(cmd, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace").strip() + + +def youtube_lane_rows(ssh) -> list[dict]: + try: + dash = json.loads(run(ssh, "curl -sS -m 15 http://127.0.0.1:8001/hub/dashboard")) + except json.JSONDecodeError: + return [] + rows = [] + for p in dash.get("live", {}).get("processes", []): + name = str(p.get("pm2") or "").strip() + if not name.startswith("youtube"): + continue + rows.append(p) + return rows + + +def lane_is_pushing(row: dict) -> bool: + if row.get("is_pushing") or row.get("ffmpeg_active"): + return True + business = str(row.get("business_status") or "").strip().lower() + return business in {"streaming", "relay_starting", "relay_slow", "source_stalled"} + + +def deploy_host(host: str, user: str, pw: str, base: str) -> None: + print(f"\n{'='*72}\n{host} {base}\n{'='*72}") + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + try: + ssh.connect(host, username=user, password=pw, timeout=25) + except Exception as exc: + print(f"SSH FAIL: {exc}") + return + + rtmps_before = run(ssh, "pgrep -af 'ffmpeg.*rtmps' 2>/dev/null | grep -v pgrep || true") + print(f"rtmps before: {len(rtmps_before.splitlines()) if rtmps_before else 0} proc(s)") + + sftp = ssh.open_sftp() + install_cmds = [] + for rel in BACKEND_FILES: + local = ROOT / rel + tmp = f"/tmp/_relay_fix_{rel.replace('/', '_')}" + dest = f"{base}/{rel.replace(chr(92), '/')}" + put_lf(sftp, local, tmp) + install_cmds.append(f"install -m 0644 {tmp} {dest}") + print("staged", rel) + + if CONSOLE_OUT.is_dir(): + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + tar.add(CONSOLE_OUT, arcname="out") + buf.seek(0) + remote_tar = "/tmp/_relay_fix_console_out.tgz" + sftp.putfo(buf, remote_tar) + install_cmds.append( + f"rm -rf {base}/web-console/out && mkdir -p {base}/web-console && " + f"tar -xzf {remote_tar} -C {base}/web-console && rm -f {remote_tar}" + ) + print("staged web-console/out") + sftp.close() + + print(run(ssh, f"echo '{pw}' | sudo -S -p '' bash -lc \"{' && '.join(install_cmds)}\"")) + + print("markers:") + print(" prune_orphan:", run(ssh, f"grep -c prune_orphan_relay_recording {base}/youtube.py")) + print(" old guard:", run(ssh, f"grep -c 'len(recording) > 0' {base}/youtube.py || echo 0")) + print(" active_monitor:", run(ssh, f"grep -c active_monitor_urls {base}/youtube.py")) + print(" hub fix:", run(ssh, f"grep -c 'url_file = Path' {base}/src/hub_routes.py")) + + print("\nrestart live-console ...") + print(run(ssh, f"echo '{pw}' | sudo -S -p '' systemctl restart live-console.service", timeout=120)) + time.sleep(4) + + lanes = youtube_lane_rows(ssh) + print(f"\nrestart youtube lanes ({len(lanes)} found):") + for row in lanes: + proc = str(row.get("pm2") or "") + if proc == "youtube": + print(f" skip {proc}: legacy") + continue + if lane_is_pushing(row): + print(f" skip {proc}: pushing (biz={row.get('business_status')})") + continue + out = run( + ssh, + f"curl -sS -m 120 -X POST 'http://127.0.0.1:8001/restart' " + f"-H 'Content-Type: application/json' " + f"-d '{{\"process\":\"{proc}\"}}'", + timeout=150, + ) + print(f" restarted {proc}: {out[:180]}") + + time.sleep(8) + rtmps_after = run(ssh, "pgrep -af 'ffmpeg.*rtmps' 2>/dev/null | grep -v pgrep || true") + print(f"\nrtmps after: {len(rtmps_after.splitlines()) if rtmps_after else 0} proc(s)") + + for row in youtube_lane_rows(ssh): + proc = str(row.get("pm2") or "") + if "youtube" not in proc.lower(): + continue + note = str(row.get("business_note") or "") + if "is_file" in note: + print(f" WARN {proc}: {note[:80]}") + else: + print( + f" {proc}: biz={row.get('business_status')} " + f"pushing={row.get('is_pushing')} online={row.get('process_status')}" + ) + + ssh.close() + + +if __name__ == "__main__": + for h, u, p, b in HOSTS: + deploy_host(h, u, p, b) + print("\nDONE") diff --git a/d2ypp2/tools/deploy_relay_log_fix_host03.py b/d2ypp2/tools/deploy_relay_log_fix_host03.py new file mode 100644 index 0000000..d5253c2 --- /dev/null +++ b/d2ypp2/tools/deploy_relay_log_fix_host03.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Deploy relay log import fix and re-import on host03.""" +from __future__ import annotations + +import io +import json +import posixpath +import sys +from pathlib import Path + +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +BASE = "/opt/live/d2ypp" +REPO = Path(__file__).resolve().parent.parent +FILES = [ + "src/youtube_relay_log.py", + "src/hub_routes.py", + "web.py", + "web-console/components/live-product/LiveYoutubeRelayLogView.tsx", + "web-console/components/live-product/LiveYoutubeUnmannedView.tsx", +] + + +def put(sftp: paramiko.SFTPClient, local: Path, remote: str) -> None: + parent = posixpath.dirname(remote) + parts = [p for p in parent.split("/") if p] + cur = "" + for part in parts: + cur = f"{cur}/{part}" if cur else f"/{part}" + try: + sftp.stat(cur) + except OSError: + try: + sftp.mkdir(cur) + except OSError: + pass + data = local.read_bytes().replace(b"\r\n", b"\n") + sftp.putfo(io.BytesIO(data), remote) + + +def run(client: paramiko.SSHClient, cmd: str, timeout: int = 180) -> tuple[int, str]: + _, stdout, stderr = client.exec_command("export LC_ALL=C.UTF-8; " + cmd, timeout=timeout) + out = (stdout.read() + stderr.read()).decode("utf-8", "replace") + return stdout.channel.recv_exit_status(), out + + +def safe_print(text: str) -> None: + try: + print(text) + except UnicodeEncodeError: + sys.stdout.buffer.write(text.encode("utf-8", errors="replace") + b"\n") + + +def main() -> int: + client = paramiko.SSHClient() + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.connect(HOST, username=USER, password=PASS, timeout=20) + sftp = client.open_sftp() + for rel in FILES: + put(sftp, REPO / rel, f"{BASE}/{rel}") + safe_print(f"uploaded {rel}") + sftp.close() + + steps = [ + f"python3 -m py_compile {BASE}/src/youtube_relay_log.py {BASE}/web.py", + f"echo {PASS!r} | sudo -S -p '' systemctl restart live-console.service", + "sleep 10", + "curl -sf http://127.0.0.1:8001/health", + ( + "curl -sS -X POST http://127.0.0.1:8001/hub/youtube/relay/sessions/import-log " + "-H 'Content-Type: application/json' " + "-d '{\"process\":\"youtube\",\"replace_imported\":true}'" + ), + "curl -sS 'http://127.0.0.1:8001/hub/youtube/relay/sessions?process=youtube&limit=20'", + ] + for step in steps: + code, out = run(client, step) + safe_print(f"\n--- exit={code} ---\n{out[:5000]}") + if step.endswith("limit=20'"): + try: + data = json.loads(out) + for row in data.get("sessions", []): + safe_print( + f" {row.get('anchor_name')} | {row.get('source_url')} | " + f"start={row.get('started_at')} dur={row.get('duration_seconds')}s | " + f"{row.get('stream_title')}" + ) + except json.JSONDecodeError: + pass + client.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/deploy_relay_log_host03.py b/d2ypp2/tools/deploy_relay_log_host03.py new file mode 100644 index 0000000..07bb116 --- /dev/null +++ b/d2ypp2/tools/deploy_relay_log_host03.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Deploy YouTube relay log feature to 10.88.0.3 and restart live-console.""" +from __future__ import annotations + +import io +import posixpath +import sys +import time +from pathlib import Path + +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +REMOTE_BASE = "/opt/live/d2ypp" +REPO = Path(__file__).resolve().parent.parent + + +def collect_files() -> list[str]: + files = [ + "src/youtube_relay_log.py", + "src/youtube_ingest_auth.py", + "src/hub_routes.py", + "web.py", + "douyin_youtube_ffplay.py", + "web-console/app/youtube-relay-log/page.tsx", + "web-console/components/live-product/LiveYoutubeRelayLogView.tsx", + "web-console/components/live-product/LiveYoutubeUnmannedView.tsx", + "web-console/components/live-product/LiveControlApp.tsx", + ] + for path in (REPO / "src").rglob("*.py"): + files.append(str(path.relative_to(REPO)).replace("\\", "/")) + out_dir = REPO / "web-console" / "out" + for path in out_dir.rglob("*"): + if path.is_file(): + files.append(str(path.relative_to(REPO)).replace("\\", "/")) + return sorted(set(files)) + + +def mkdir_p(sftp: paramiko.SFTPClient, remote_dir: str) -> None: + remote_dir = remote_dir.rstrip("/") + if not remote_dir or remote_dir == "/": + return + cur = "" + for part in [p for p in remote_dir.split("/") if p]: + cur = f"{cur}/{part}" if cur else f"/{part}" + try: + sftp.stat(cur) + except OSError: + try: + sftp.mkdir(cur) + except OSError: + pass + + +def put(sftp: paramiko.SFTPClient, local: Path, remote: str) -> None: + mkdir_p(sftp, posixpath.dirname(remote)) + if local.suffix.lower() in {".py", ".sh", ".tsx", ".ts", ".mjs"}: + data = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + sftp.putfo(io.BytesIO(data), remote) + else: + sftp.put(str(local), remote) + + +def run(client: paramiko.SSHClient, cmd: str, timeout: int = 120) -> tuple[int, str]: + _, stdout, stderr = client.exec_command( + "export LC_ALL=C.UTF-8 LANG=C.UTF-8; " + cmd, + timeout=timeout, + ) + out = (stdout.read() + stderr.read()).decode("utf-8", "replace") + return stdout.channel.recv_exit_status(), out + + +def main() -> int: + files = collect_files() + client = paramiko.SSHClient() + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.connect(HOST, username=USER, password=PASS, timeout=20) + sftp = client.open_sftp() + + print(f"Uploading {len(files)} files to {REMOTE_BASE} ...") + for idx, rel in enumerate(files, start=1): + local = REPO / rel + if not local.is_file(): + print(f"SKIP missing: {rel}") + continue + put(sftp, local, f"{REMOTE_BASE}/{rel}") + if idx <= 5 or idx == len(files) or idx % 40 == 0: + print(f" {idx}/{len(files)} {rel}") + sftp.close() + + steps = [ + f"rm -rf {REMOTE_BASE}/src/__pycache__ 2>/dev/null; echo cache_cleared", + ( + f"python3 -m py_compile {REMOTE_BASE}/src/youtube_relay_log.py " + f"{REMOTE_BASE}/web.py {REMOTE_BASE}/src/hub_routes.py; echo syntax_ok" + ), + f"echo {PASS!r} | sudo -S -p '' systemctl restart live-console.service; echo restarted", + "sleep 10", + "for i in 1 2 3 4 5 6 7 8 9 10 11 12; do " + "curl -sf -m 4 http://127.0.0.1:8001/health >/dev/null 2>&1 && echo health_ok && break; " + "sleep 3; done", + ( + "curl -sS -m 8 -o /dev/null -w 'relay_log_page=%{http_code}\\n' " + "http://127.0.0.1:8001/youtube-relay-log" + ), + ( + "curl -sS -m 8 'http://127.0.0.1:8001/hub/youtube/relay/sessions?limit=1' " + "| head -c 500; echo" + ), + ( + "curl -sS -m 8 -X POST 'http://127.0.0.1:8001/hub/youtube/relay/sessions/import-log' " + "-H 'Content-Type: application/json' -d '{\"process\":\"youtube\"}' | head -c 500; echo" + ), + "systemctl is-active live-console.service 2>/dev/null; journalctl -u live-console.service -n 15 --no-pager 2>/dev/null", + ] + for step in steps: + code, out = run(client, step, timeout=180) + try: + print(f"\n--- exit={code} ---\n{out.strip()[:1200]}") + except UnicodeEncodeError: + sys.stdout.buffer.write(f"\n--- exit={code} ---\n".encode()) + sys.stdout.buffer.write(out.strip()[:1200].encode("utf-8", errors="replace") + b"\n") + + client.close() + print("\nDeploy complete.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/deploy_relay_slot_fix_237.py b/d2ypp2/tools/deploy_relay_slot_fix_237.py new file mode 100644 index 0000000..6675b25 --- /dev/null +++ b/d2ypp2/tools/deploy_relay_slot_fix_237.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Deploy relay-slot fix to 192.168.2.237 and restart active youtube lane.""" +from __future__ import annotations + +import io +import json +import paramiko +from pathlib import Path + +HOST, USER, PW = "192.168.2.237", "eric", "4669805" +BASE = "/home/eric/d2ypp2-src" +ROOT = Path(__file__).resolve().parent.parent +FILES = [ + "src/youtube_relay_slot.py", + "youtube.py", + "douyin_youtube_ffplay.py", + "src/hub_routes.py", +] +PROC = "youtube2__ch_mpwri36r_z5lm2" + + +def put_lf(sftp, local: Path, remote: str) -> None: + data = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + sftp.putfo(io.BytesIO(data), remote) + + +def run(ssh, cmd, timeout=120): + _, o, e = ssh.exec_command(cmd, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace").strip() + + +ssh = paramiko.SSHClient() +ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +ssh.connect(HOST, username=USER, password=PW, timeout=25) +sftp = ssh.open_sftp() +install_cmds = [] +for rel in FILES: + local = ROOT / rel + tmp = f"/tmp/_deploy_{rel.replace('/', '_')}" + dest = f"{BASE}/{rel.replace(chr(92), '/')}" + put_lf(sftp, local, tmp) + mode = "0644" + install_cmds.append(f"install -m {mode} {tmp} {dest}") + print("staged", rel) +sftp.close() +print(run(ssh, f"echo '{PW}' | sudo -S -p '' bash -lc \"{' && '.join(install_cmds)}\"")) + +print("\n=== restart lane ===") +print( + run( + ssh, + f"curl -sS -m 90 -X POST 'http://127.0.0.1:8001/restart' " + f"-H 'Content-Type: application/json' " + f"-d '{{\"process\":\"{PROC}\"}}'", + ) +) + +import time + +time.sleep(8) +print("\n=== ffmpeg ===") +print(run(ssh, "pgrep -af 'ffmpeg.*rtmps' | grep -v pgrep | head -2 || echo none")) +print("\n=== log tail ===") +print(run(ssh, f"tail -20 {BASE}/.pm2/logs/{PROC}-out.log")) +print("\n=== dashboard ===") +dash = json.loads(run(ssh, "curl -sS -m 12 http://127.0.0.1:8001/hub/dashboard")) +for p in dash.get("live", {}).get("processes", []): + if PROC in p.get("pm2", ""): + print( + p.get("pm2"), + p.get("business_status"), + "pushing=", + p.get("is_pushing"), + "note=", + (p.get("business_note") or "")[:120], + ) +ssh.close() diff --git a/d2ypp2/tools/deploy_relay_slot_fix_3hosts_safe.py b/d2ypp2/tools/deploy_relay_slot_fix_3hosts_safe.py new file mode 100644 index 0000000..7f634ec --- /dev/null +++ b/d2ypp2/tools/deploy_relay_slot_fix_3hosts_safe.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Deploy relay-slot fix to 3 hosts without restarting lanes that are actively pushing.""" +from __future__ import annotations + +import io +import json +import paramiko +import re +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +FILES = [ + "src/youtube_relay_slot.py", + "youtube.py", + "douyin_youtube_ffplay.py", + "src/hub_routes.py", +] + +HOSTS = [ + ("192.168.2.237", "eric", "4669805", "/home/eric/d2ypp2-src"), + ("10.88.0.3", "eric", "Xiao4669805", "/opt/live/d2ypp"), + ("10.88.0.5", "eric", "4669805", "/opt/live/d2ypp"), +] + + +def put_lf(sftp, local: Path, remote: str) -> None: + data = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + sftp.putfo(io.BytesIO(data), remote) + + +def run(ssh, cmd, timeout=180): + _, o, e = ssh.exec_command(cmd, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace").strip() + + +def active_rtmps_pids(ssh) -> list[str]: + out = run(ssh, "pgrep -af 'ffmpeg.*rtmps' 2>/dev/null | grep -v pgrep || true") + if not out: + return [] + return [line for line in out.splitlines() if "ffmpeg" in line.lower()] + + +def youtube_procs(ssh) -> list[dict]: + try: + dash = json.loads(run(ssh, "curl -sS -m 15 http://127.0.0.1:8001/hub/dashboard")) + except json.JSONDecodeError: + return [] + rows = [] + for p in dash.get("live", {}).get("processes", []): + name = str(p.get("pm2") or "").strip() + if not name.startswith("youtube"): + continue + rows.append( + { + "pm2": name, + "status": p.get("process_status"), + "pushing": p.get("is_pushing"), + "ffmpeg_active": p.get("ffmpeg_active"), + } + ) + return rows + + +def lane_push_state(ssh, proc: str, rtmps_lines: list[str]) -> str: + """Return: pushing | online | stopped""" + if any(proc in line or "youtube.py" in line for line in rtmps_lines): + # weak match: any rtmps while this host has one youtube lane pushing + pass + out = run(ssh, f"ps aux | grep -E '[p]ython.*youtube\\.py' | head -5") + # If only one youtube.py and rtmps active, treat as pushing for all pro lanes on small hosts + if rtmps_lines and "online" in str(youtube_procs(ssh)): + for row in youtube_procs(ssh): + if row["pm2"] == proc and (row.get("pushing") or row.get("ffmpeg_active")): + return "pushing" + try: + dash = json.loads(run(ssh, "curl -sS -m 15 http://127.0.0.1:8001/hub/dashboard")) + for p in dash.get("live", {}).get("processes", []): + if p.get("pm2") == proc: + if p.get("is_pushing") or p.get("ffmpeg_active"): + return "pushing" + st = str(p.get("process_status") or "").lower() + if st in {"online", "running", "launching"}: + return "online" + return "stopped" + except json.JSONDecodeError: + pass + return "unknown" + + +for host, user, pw, base in HOSTS: + print(f"\n{'='*72}\n{host} {base}\n{'='*72}") + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + try: + ssh.connect(host, username=user, password=pw, timeout=25) + except Exception as exc: + print(f"SSH FAIL: {exc}") + continue + + rtmps_before = active_rtmps_pids(ssh) + print(f"rtmps before ({len(rtmps_before)}):") + for line in rtmps_before[:3]: + print(" ", line[:160]) + + sftp = ssh.open_sftp() + install_cmds = [] + for rel in FILES: + local = ROOT / rel + tmp = f"/tmp/_relay_slot3_{rel.replace('/', '_')}" + dest = f"{base}/{rel.replace(chr(92), '/')}" + put_lf(sftp, local, tmp) + install_cmds.append(f"install -m 0644 {tmp} {dest}") + print("staged", rel) + sftp.close() + print(run(ssh, f"echo '{pw}' | sudo -S -p '' bash -lc \"{' && '.join(install_cmds)}\"")) + + print("markers:") + print(" relay_slot:", run(ssh, f"test -f {base}/src/youtube_relay_slot.py && echo present")) + print(" prune_orphan:", run(ssh, f"grep -c prune_orphan_relay_recording {base}/youtube.py")) + print(" old guard:", run(ssh, f"grep -c 'len(recording) > 0' {base}/youtube.py || echo 0")) + print(" hub fix:", run(ssh, f"grep -c 'url_file = Path' {base}/src/hub_routes.py")) + + print("\nrestart live-console only (does not touch youtube.py workers)...") + print(run(ssh, f"echo '{pw}' | sudo -S -p '' systemctl restart live-console.service", timeout=120)) + time.sleep(3) + + procs = [r["pm2"] for r in youtube_procs(ssh)] + print("\nlane restart policy:") + for proc in procs: + if proc == "youtube": + print(f" skip {proc}: legacy single process") + continue + state = lane_push_state(ssh, proc, rtmps_before) + if state == "pushing" or rtmps_before: + print(f" skip {proc}: keep running (host has active rtmps or lane pushing)") + else: + print(f" skip {proc}: no restart (preserve monitoring loop; code loads on next restart)") + + rtmps_after = active_rtmps_pids(ssh) + print(f"\nrtmps after ({len(rtmps_after)}):") + for line in rtmps_after[:3]: + print(" ", line[:160]) + if rtmps_before and not rtmps_after: + print(" WARNING: rtmps disappeared — investigate!") + elif len(rtmps_before) <= len(rtmps_after): + print(" OK: no push interruption detected") + + dash = json.loads(run(ssh, "curl -sS -m 15 http://127.0.0.1:8001/hub/dashboard")) + for p in dash.get("live", {}).get("processes", []): + if "youtube" in str(p.get("pm2", "")).lower(): + note = str(p.get("business_note") or "") + if "is_file" in note: + print(f" WARN {p.get('pm2')}: {note[:80]}") + else: + print( + f" {p.get('pm2')}: biz={p.get('business_status')} " + f"pushing={p.get('is_pushing')}" + ) + + ssh.close() + +print("\nDONE — youtube.py / ffplay changes on disk; active workers keep old code until next lane restart.") diff --git a/d2ypp2/tools/deploy_relay_slot_fix_host03_host05.py b/d2ypp2/tools/deploy_relay_slot_fix_host03_host05.py new file mode 100644 index 0000000..9b046e4 --- /dev/null +++ b/d2ypp2/tools/deploy_relay_slot_fix_host03_host05.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Deploy relay-slot fix to 10.88.0.3 and 10.88.0.5, restart youtube lanes + live-console.""" +from __future__ import annotations + +import io +import json +import paramiko +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +FILES = [ + "src/youtube_relay_slot.py", + "youtube.py", + "douyin_youtube_ffplay.py", + "src/hub_routes.py", +] + +HOSTS = [ + ("10.88.0.3", "eric", "Xiao4669805", "/opt/live/d2ypp"), + ("10.88.0.5", "eric", "4669805", "/opt/live/d2ypp"), +] + + +def put_lf(sftp, local: Path, remote: str) -> None: + data = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + sftp.putfo(io.BytesIO(data), remote) + + +def run(ssh, cmd, timeout=180): + _, o, e = ssh.exec_command(cmd, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace").strip() + + +def youtube_procs(ssh) -> list[str]: + raw = run(ssh, "curl -sS -m 15 http://127.0.0.1:8001/hub/dashboard") + try: + dash = json.loads(raw) + except json.JSONDecodeError: + return [] + out = [] + for p in dash.get("live", {}).get("processes", []): + name = str(p.get("pm2") or "").strip() + if name.startswith("youtube2__") or name == "youtube": + out.append(name) + return out + + +for host, user, pw, base in HOSTS: + print(f"\n{'='*72}\n{host} {base}\n{'='*72}") + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(host, username=user, password=pw, timeout=25) + + print("before old guard:", run(ssh, f"grep -n 'len(recording) > 0' {base}/youtube.py | head -1 || echo fixed")) + + sftp = ssh.open_sftp() + install_cmds = [] + for rel in FILES: + local = ROOT / rel + tmp = f"/tmp/_relay_slot_{rel.replace('/', '_')}" + dest = f"{base}/{rel.replace(chr(92), '/')}" + put_lf(sftp, local, tmp) + install_cmds.append(f"install -m 0644 {tmp} {dest}") + print("staged", rel) + sftp.close() + print(run(ssh, f"echo '{pw}' | sudo -S -p '' bash -lc \"{' && '.join(install_cmds)}\"")) + + print("after markers:") + print(" relay_slot:", run(ssh, f"test -f {base}/src/youtube_relay_slot.py && echo present")) + print(" old guard:", run(ssh, f"grep -c 'len(recording) > 0' {base}/youtube.py || true")) + print(" stream filter:", run(ssh, f"grep -c '_is_probable_stream_input' {base}/douyin_youtube_ffplay.py || true")) + + print("\nrestart live-console ...") + print(run(ssh, f"echo '{pw}' | sudo -S -p '' systemctl restart live-console.service", timeout=120)) + time.sleep(4) + + procs = youtube_procs(ssh) + print("restart lanes:", procs) + for proc in procs: + if proc == "youtube": + continue + out = run( + ssh, + f"curl -sS -m 120 -X POST 'http://127.0.0.1:8001/restart' " + f"-H 'Content-Type: application/json' " + f"-d '{{\"process\":\"{proc}\"}}'", + timeout=150, + ) + print(f" {proc}: {out[:220]}") + + time.sleep(10) + print("\nverify ffmpeg:", run(ssh, "pgrep -af 'ffmpeg.*rtmps' | grep -v pgrep | head -2 || echo none")) + dash = json.loads(run(ssh, "curl -sS -m 15 http://127.0.0.1:8001/hub/dashboard")) + for p in dash.get("live", {}).get("processes", []): + if "youtube" in str(p.get("pm2", "")).lower(): + note = str(p.get("business_note") or "") + print( + f" {p.get('pm2')}: biz={p.get('business_status')} pushing={p.get('is_pushing')} " + f"note={note[:70]}" + ) + ssh.close() + +print("\nDONE") diff --git a/d2ypp2/tools/grep_host03_youtube_log.py b/d2ypp2/tools/grep_host03_youtube_log.py new file mode 100644 index 0000000..2b19b48 --- /dev/null +++ b/d2ypp2/tools/grep_host03_youtube_log.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +import paramiko +import sys + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" + +def run(cmd): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _, o, e = c.exec_command(cmd, timeout=180, get_pty=True) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + +cmds = [ + "echo Xiao4669805 | sudo -S grep '正在录制 1 路' /root/.pm2/logs/youtube-out.log | grep '原画 2:05:' | tail -20", + "echo Xiao4669805 | sudo -S grep '正在录制 1 路' /root/.pm2/logs/youtube-out.log | grep '2026-06-24T07:' | tail -25", + "echo Xiao4669805 | sudo -S grep '正在录制 1 路' /root/.pm2/logs/youtube-out.log | grep '2026-06-24' | grep -E '原画 2:0[4-6]:' | tail -30", + "echo Xiao4669805 | sudo -S grep '正在录制 1 路' /root/.pm2/logs/youtube-out.log | grep '2026-06-24T06:' | grep -E '原画 2:' | tail -20", +] + +for cmd in cmds: + print("===", cmd[:90], "===") + sys.stdout.buffer.write(run(cmd).encode("utf-8", "replace")[:15000]) + print() diff --git a/d2ypp2/tools/inspect_pm2_log_sudo_host03.py b/d2ypp2/tools/inspect_pm2_log_sudo_host03.py new file mode 100644 index 0000000..8d93c6c --- /dev/null +++ b/d2ypp2/tools/inspect_pm2_log_sudo_host03.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +import paramiko, sys +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +cmds = [ + f"echo {PASS!r} | sudo -S wc -l /root/.pm2/logs/youtube-out.log 2>/dev/null", + f"echo {PASS!r} | sudo -S grep -E '开始推流到 YouTube|正在录制 1' /root/.pm2/logs/youtube-out.log 2>/dev/null | head -8", + f"echo {PASS!r} | sudo -S grep -E '开始推流到 YouTube|正在录制 1' /root/.pm2/logs/youtube-out.log 2>/dev/null | tail -8", + f"echo {PASS!r} | sudo -S grep '又系_柠檬茶\\|745277409780\\|柠檬茶' /root/.pm2/logs/youtube-out.log 2>/dev/null | head -20", + f"echo {PASS!r} | sudo -S grep '开始推流到 YouTube' /root/.pm2/logs/youtube-out.log 2>/dev/null | wc -l", + f"echo {PASS!r} | sudo -S ls -la /opt/live/d2ypp/.pm2/logs/youtube-out.log /root/.pm2/logs/youtube-out.log 2>/dev/null", +] +c = paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()); c.connect(HOST, username=USER, password=PASS, timeout=20) +for cmd in cmds: + _, o, e = c.exec_command(cmd, timeout=120) + out = (o.read() + e.read()).decode('utf-8', 'replace') + sys.stdout.buffer.write(f"\n=== {cmd[:90]} ===\n{out[:5000]}\n".encode('utf-8','replace')) +c.close() diff --git a/d2ypp2/tools/inspect_relay_log_host03.py b/d2ypp2/tools/inspect_relay_log_host03.py new file mode 100644 index 0000000..0e75ad1 --- /dev/null +++ b/d2ypp2/tools/inspect_relay_log_host03.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Inspect relay log DB and PM2 log samples on host03.""" +from __future__ import annotations + +import json +import sys + +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +BASE = "/opt/live/d2ypp" + + +def run(cmd: str, timeout: int = 180) -> str: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=20) + _, o, e = c.exec_command("export LC_ALL=C.UTF-8 LANG=C.UTF-8; " + cmd, timeout=timeout) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +cmds = [ + "curl -sS 'http://127.0.0.1:8001/hub/youtube/relay/sessions?process=youtube&limit=20' | python3 -m json.tool 2>/dev/null | head -120", + f"sqlite3 {BASE}/config/hub_state.sqlite \"SELECT id, anchor_name, datetime(started_at,'unixepoch','localtime'), datetime(ended_at,'unixepoch','localtime'), duration_seconds, source_url, stream_title FROM youtube_relay_sessions ORDER BY started_at DESC LIMIT 15\" 2>/dev/null", + "grep -E '开始推流到 YouTube|正在录制 1|推流已彻底停止|准备开始录制' /root/.pm2/logs/youtube-out.log 2>/dev/null | tail -30", + "grep -E '开始推流到 YouTube|正在录制 1' /root/.pm2/logs/youtube-out.log 2>/dev/null | head -15", + f"cat {BASE}/config/URL_config.youtube.ini 2>/dev/null | head -30", + "wc -l /root/.pm2/logs/youtube-out.log 2>/dev/null", +] +for cmd in cmds: + sys.stdout.buffer.write(f"\n=== {cmd[:100]} ===\n".encode()) + sys.stdout.buffer.write(run(cmd)[:6000].encode("utf-8", "replace") + b"\n") diff --git a/d2ypp2/tools/query_host03_api.py b/d2ypp2/tools/query_host03_api.py new file mode 100644 index 0000000..30af145 --- /dev/null +++ b/d2ypp2/tools/query_host03_api.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +import json +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" + +def q(cmd): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _, o, e = c.exec_command(cmd, timeout=60, get_pty=True) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + +for label, cmd in [ + ("events_api", "curl -sS -m 20 'http://127.0.0.1:8001/hub/youtube/live/events?limit=20&process=youtube'"), + ("event67", "curl -sS -m 20 'http://127.0.0.1:8001/hub/youtube/live/events/67'"), + ("ffmpeg_ps", "ps aux | grep 'ffmpeg.*rtmps' | grep -v grep"), + ("youtube_ps", "ps -p 3775019 -o lstart,etime,cmd 2>/dev/null || ps aux | grep youtube.py | grep -v grep"), +]: + print(f"\n=== {label} ===") + out = q(cmd) + try: + print(json.dumps(json.loads(out), ensure_ascii=False, indent=2)[:12000]) + except Exception: + print(out[:6000]) diff --git a/d2ypp2/tools/query_host03_downloads.py b/d2ypp2/tools/query_host03_downloads.py new file mode 100644 index 0000000..741730e --- /dev/null +++ b/d2ypp2/tools/query_host03_downloads.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +REMOTE = r''' +import os, glob, time +from datetime import datetime + +base="/opt/live/d2ypp/downloads" +hits=[] +for path in glob.glob(base + "/**/*", recursive=True): + try: + if not os.path.isfile(path): continue + m=os.path.getmtime(path) + hits.append((m, path, os.path.getsize(path))) + except: pass +hits.sort(reverse=True) +print('total files', len(hits)) +for m,p,s in hits[:60]: + print(datetime.fromtimestamp(m).isoformat(), round(s/1024/1024,1), 'MB', p) + +print('\n=== files between 05:00-08:00 ===') +for m,p,s in hits: + ts=datetime.fromtimestamp(m) + if ts.date().isoformat()=='2026-06-24' and 5 <= ts.hour < 8: + print(ts.isoformat(), round(s/1024/1024,1), 'MB', p) +''' + +def main(): + c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _,o,e=c.exec_command(f"python3 - <<'PY'\n{REMOTE}\nPY", timeout=120, get_pty=True) + import sys; sys.stdout.buffer.write((o.read()+e.read())[:30000]) + c.close() +if __name__=='__main__': main() diff --git a/d2ypp2/tools/query_host03_journal.py b/d2ypp2/tools/query_host03_journal.py new file mode 100644 index 0000000..c2e7dd9 --- /dev/null +++ b/d2ypp2/tools/query_host03_journal.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" + +REMOTE = r''' +import subprocess, re + +def run(cmd): + return subprocess.check_output(cmd, shell=True, text=True, errors='replace') + +for cmd in [ + "journalctl -u live-console.service --since '2026-06-24 04:30' --until '2026-06-24 08:30' 2>/dev/null | grep -E '正在录制|live.douyin.com/[0-9]|录制 1 路|YOUTUBE' | tail -80", + "journalctl --since '2026-06-24 04:30' --until '2026-06-24 08:30' 2>/dev/null | grep -E 'youtube.py|正在录制|live.douyin.com/[0-9]{6,}' | tail -80", + "ls -la /proc/3775019/fd 2>/dev/null | head -20", + "readlink /proc/3775019/fd/1 /proc/3775019/fd/2 2>/dev/null", +]: + print('===', cmd[:100], '===') + try: + print(run(cmd)[:12000]) + except Exception as e: + print('ERR', e) +''' + +def main(): + c = paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _,o,e = c.exec_command(f"python3 - <<'PY'\n{REMOTE}\nPY", timeout=180, get_pty=True) + print((o.read()+e.read()).decode('utf-8','replace')[:25000]) + c.close() + +if __name__ == '__main__': + main() diff --git a/d2ypp2/tools/query_host03_lane1.py b/d2ypp2/tools/query_host03_lane1.py new file mode 100644 index 0000000..d51bc2f --- /dev/null +++ b/d2ypp2/tools/query_host03_lane1.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Query 10.88.0.3 YouTube lane 1 config and recent logs.""" +from __future__ import annotations + +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +BASE = "/home/eric/d2ypp2-src" + + +def q(cmd: str, timeout: int = 90) -> str: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +CMDS = [ + ("identity", f"hostname; ls -d {BASE} /opt/live/d2ypp 2>/dev/null"), + ("pm2", f"PM2_HOME={BASE}/.pm2 pm2 list 2>/dev/null | head -30"), + ("ini_files", f"ls -la {BASE}/config/youtube.youtube2__*.ini {BASE}/config/url.youtube2__*.ini 2>/dev/null"), + ( + "hub_db", + f"find {BASE} -maxdepth 3 \\( -name '*.db' -o -name 'hub*.json' \\) 2>/dev/null | head -20", + ), + ( + "youtube_pro_kv", + f"""python3 - <<'PY' +import sqlite3, json, glob, os +base = '{BASE}' +paths = glob.glob(base + '/data/*.db') + glob.glob(base + '/.hub/*.db') + glob.glob(base + '/**/*.db', recursive=True) +seen = set() +for p in paths: + if p in seen: continue + seen.add(p) + try: + conn = sqlite3.connect(p) + rows = conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall() + if not rows: continue + for key in ('youtube_pro_channels_v1',): + try: + r = conn.execute('SELECT value FROM kv WHERE key=?', (key,)).fetchone() + if r: + print('DB', p) + print(r[0][:12000]) + except Exception: + pass + conn.close() + except Exception as e: + pass +PY""", + ), + ( + "all_ini", + f"for f in {BASE}/config/youtube.youtube2__*.ini; do echo '=== $f ==='; cat \"$f\"; done 2>/dev/null", + ), + ( + "all_url_ini", + f"for f in {BASE}/config/url.youtube2__*.ini; do echo '=== $f ==='; cat \"$f\"; done 2>/dev/null", + ), + ( + "logs_lane1", + f"ls -la {BASE}/.pm2/logs/youtube2__*-out.log 2>/dev/null | head -20", + ), + ( + "grep_douyin_logs", + f"grep -hE 'live.douyin.com|douyin.com/[0-9]|source|拉流|stream_url|web data' {BASE}/.pm2/logs/youtube2__*-out.log 2>/dev/null | tail -80", + ), + ( + "grep_12h", + f"find {BASE}/.pm2/logs -name 'youtube2__*-out.log' -mmin -900 2>/dev/null | while read f; do echo '=== $f ==='; grep -E 'live.douyin.com|start|stop|推流|duration|session' \"$f\" | tail -30; done", + ), + ( + "process_monitor", + "curl -sS -m 15 'http://127.0.0.1:8001/process_monitor?family=youtube' 2>/dev/null | head -c 8000", + ), +] + + +def main() -> int: + for label, cmd in CMDS: + print(f"\n{'=' * 60}\n=== {label} ===\n{'=' * 60}") + try: + out = q(cmd) + print(out[:12000].encode("ascii", "backslashreplace").decode()) + except Exception as exc: + print(f"ERR: {exc}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/query_host03_lane1_deep.py b/d2ypp2/tools/query_host03_lane1_deep.py new file mode 100644 index 0000000..0572bf3 --- /dev/null +++ b/d2ypp2/tools/query_host03_lane1_deep.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Deep query 10.88.0.3 for lane1 history and douyin source.""" +from __future__ import annotations + +import json +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +BASE = "/home/eric/d2ypp2-src" + + +def q(cmd: str, timeout: int = 120) -> str: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +CMDS = [ + ("pm2_full", f"PM2_HOME={BASE}/.pm2 pm2 jlist 2>/dev/null"), + ("pm2_desc", f"PM2_HOME={BASE}/.pm2 pm2 describe youtube 2>/dev/null; PM2_HOME={BASE}/.pm2 pm2 describe youtube2__ch_mpykhmnj_lsrv7 2>/dev/null"), + ("youtube_ini", f"cat {BASE}/config/youtube.ini 2>/dev/null; echo '---'; cat {BASE}/config/url.ini 2>/dev/null; echo '---'; ls -la {BASE}/config/*.ini 2>/dev/null"), + ("hub_files", f"find {BASE} -type f \\( -name '*.db' -o -name '*youtube*' -o -name '*hub*' \\) 2>/dev/null | head -40"), + ("grep_all_logs", f"grep -rE 'live.douyin.com|source_url|source_room|线路|lane' {BASE}/.pm2/logs {BASE}/logs 2>/dev/null | tail -100"), + ("youtube_events", "curl -sS -m 20 'http://127.0.0.1:8001/hub/youtube-events?limit=50' 2>/dev/null | head -c 15000"), + ("hub_channels", "curl -sS -m 20 'http://127.0.0.1:8001/hub/youtube-pro-channels' 2>/dev/null | head -c 15000"), + ("state_json", f"cat {BASE}/.process_runner/state.json 2>/dev/null | head -c 8000"), + ("ffmpeg_cmd", "ps aux | grep -E 'ffmpeg|youtube.py' | grep -v grep"), + ("log_sizes", f"find {BASE}/.pm2/logs {BASE}/logs -type f -name '*.log' -printf '%T@ %TY-%Tm-%Td %TH:%TM %p %s\\n' 2>/dev/null | sort -nr | head -30"), + ("youtube_out_log", f"tail -200 {BASE}/.pm2/logs/youtube-out.log 2>/dev/null; tail -200 {BASE}/logs/youtube.log 2>/dev/null"), + ("grep_duration", f"grep -rE '125|2:05|2小时|7650|7500|session|duration|started|stopped' {BASE}/.pm2/logs {BASE}/logs 2>/dev/null | tail -50"), +] + + +def main() -> int: + for label, cmd in CMDS: + print(f"\n{'='*60}\n=== {label} ===\n{'='*60}") + try: + out = q(cmd) + # try pretty json + if label in ("youtube_events", "hub_channels", "pm2_full", "state_json") and out.strip().startswith(("{", "[")): + try: + print(json.dumps(json.loads(out), ensure_ascii=False, indent=2)[:15000]) + continue + except Exception: + pass + print(out[:15000].encode("ascii", "backslashreplace").decode()) + except Exception as exc: + print(f"ERR: {exc}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/query_host03_lane1_samples.py b/d2ypp2/tools/query_host03_lane1_samples.py new file mode 100644 index 0000000..582503d --- /dev/null +++ b/d2ypp2/tools/query_host03_lane1_samples.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Detailed lane1 event samples around 12h ago on 10.88.0.3.""" +from __future__ import annotations + +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" + +REMOTE_PY = r''' +import sqlite3, json, time +from datetime import datetime + +p = "/opt/live/d2ypp/config/hub_state.sqlite" +conn = sqlite3.connect(p) +conn.row_factory = sqlite3.Row +now = time.time() +target = now - 12*3600 +print("target_12h", datetime.fromtimestamp(target).isoformat()) + +# lane1 events on Jun 24 +rows = conn.execute( + """SELECT * FROM youtube_live_events + WHERE process='youtube' AND started_at > ? + ORDER BY started_at DESC""", + (now - 24*3600,), +).fetchall() +print("\n=== lane1 events last 24h ===") +for r in rows: + d = dict(r) + for k in ("started_at","ended_at","last_seen_at"): + if d.get(k): + d[k] = datetime.fromtimestamp(float(d[k])).isoformat() + d["dur_min"] = round(float(dict(r).get("duration_seconds") or 0)/60, 1) + print(json.dumps({k:d[k] for k in ["id","source_room_id","source_url","status","started_at","ended_at","dur_min"]}, ensure_ascii=False)) + +# samples for event 67 +print("\n=== samples event 67 (distinct sources) ===") +samples = conn.execute( + """SELECT ts, page_url, page_title, payload_json + FROM youtube_live_samples WHERE event_id=67 ORDER BY ts""" +).fetchall() +seen = set() +for s in samples: + d = dict(s) + ts = datetime.fromtimestamp(float(d["ts"])).isoformat() + url = d.get("page_url") or "" + title = d.get("page_title") or "" + payload = d.get("payload_json") or "" + key = url[:80] + title[:40] + if key in seen: + continue + seen.add(key) + if "douyin" in url.lower() or "douyin" in payload.lower() or "room" in payload.lower(): + print(ts, url[:120], title[:60], payload[:200]) + +print("sample_count", len(samples), "distinct", len(seen)) + +# all events with duration 7200-7800 (2h-2h10m) +print("\n=== duration 7200-7800s all time ===") +rows2 = conn.execute( + """SELECT id, process, source_room_id, source_url, duration_seconds, started_at, ended_at + FROM youtube_live_events + WHERE duration_seconds BETWEEN 7200 AND 7800 + ORDER BY started_at DESC LIMIT 20""" +).fetchall() +for r in rows2: + d = dict(r) + d["started_at"] = datetime.fromtimestamp(float(d["started_at"])).isoformat() + if d.get("ended_at"): + d["ended_at"] = datetime.fromtimestamp(float(d["ended_at"])).isoformat() + d["dur_hm"] = f"{int(d['duration_seconds']//3600)}h{int((d['duration_seconds']%3600)//60)}m" + print(json.dumps(d, ensure_ascii=False)) + +# events for lane1 where ended_at near 12h ago +/- 2h +print("\n=== lane1 ended near 12h ago ===") +rows3 = conn.execute( + """SELECT id, source_room_id, source_url, duration_seconds, started_at, ended_at + FROM youtube_live_events + WHERE process='youtube' AND ended_at BETWEEN ? AND ? + ORDER BY ended_at DESC""", + (target - 2*3600, target + 2*3600), +).fetchall() +for r in rows3: + d = dict(r) + d["started_at"] = datetime.fromtimestamp(float(d["started_at"])).isoformat() + d["ended_at"] = datetime.fromtimestamp(float(d["ended_at"])).isoformat() + d["dur_min"] = round(float(d["duration_seconds"])/60, 1) + print(json.dumps(d, ensure_ascii=False)) + +# snapshot_json from event 67 +r67 = conn.execute("SELECT snapshot_json FROM youtube_live_events WHERE id=67").fetchone() +if r67 and r67[0]: + print("\n=== event 67 snapshot ===") + print(r67[0][:3000]) + +conn.close() +''' + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _, o, e = c.exec_command(f"python3 - <<'PY'\n{REMOTE_PY}\nPY", timeout=90, get_pty=True) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + return 0 + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/query_host03_log_source.py b/d2ypp2/tools/query_host03_log_source.py new file mode 100644 index 0000000..cd6706c --- /dev/null +++ b/d2ypp2/tools/query_host03_log_source.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +REMOTE = r''' +import os, subprocess + +pid=3775019 +for cmd in [ + f"systemctl status live-console.service 2>/dev/null | head -20", + f"cat /proc/{pid}/cgroup 2>/dev/null", + f"readlink -f /proc/{pid}/fd/1 /proc/{pid}/fd/2 2>/dev/null", + f"ls -la /proc/{pid}/fd/ 2>/dev/null | head -30", + "find /opt/live/d2ypp -name '*.log' -size +0 2>/dev/null", + "find /var/log -name '*youtube*' -o -name '*live*' 2>/dev/null | head -20", + "grep -r '正在录制 1 路' /opt/live/d2ypp/logs /opt/live/d2ypp/.pm2/logs /var/log 2>/dev/null | tail -5", +]: + print('===', cmd[:90], '===') + try: + print(subprocess.check_output(cmd, shell=True, text=True, errors='replace')[:4000]) + except Exception as e: + print('ERR', e) + +# search big log files for morning recording with 2:05 duration +import glob, re +from datetime import datetime +for path in glob.glob('/opt/live/d2ypp/**', recursive=True): + try: + if not os.path.isfile(path) or os.path.getsize(path) < 100: continue + if os.path.getsize(path) > 20_000_000: continue + with open(path,'r',errors='replace') as f: + txt=f.read() + if '正在录制 1 路' in txt and '2026-06-24T0' in txt: + for line in txt.split('\n'): + if '正在录制 1 路' in line and ('06:' in line or '07:' in line or '08:' in line): + if '原画 2:0' in line or '原画 2:1' in line or '原画 2:05' in line or '原画 2:04' in line: + print('HIT', path) + print(line[:250]) + except: pass +''' + +def main(): + c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _,o,e=c.exec_command(f"python3 - <<'PY'\n{REMOTE}\nPY", timeout=180, get_pty=True) + import sys; sys.stdout.buffer.write((o.read()+e.read())[:30000]) + c.close() +if __name__=='__main__': main() diff --git a/d2ypp2/tools/query_host03_logs_morning.py b/d2ypp2/tools/query_host03_logs_morning.py new file mode 100644 index 0000000..347433f --- /dev/null +++ b/d2ypp2/tools/query_host03_logs_morning.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Search host03 logs for douyin room at ~07:00 today.""" +from __future__ import annotations + +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +BASE = "/opt/live/d2ypp" + +REMOTE = f''' +import os, re, glob +from datetime import datetime + +patterns = [ + f"{BASE}/logs/*.log", + f"{BASE}/.pm2/logs/*.log", + "/var/log/syslog", + "/tmp/*.log", +] +needles = ["live.douyin.com", "source_room", "629587976874", "288944177940", "334176667239", "切换", "Douyin", "web data"] +for pat in patterns: + for path in glob.glob(pat): + try: + if os.path.getsize(path) == 0: + continue + with open(path, "r", errors="replace") as f: + hits = [] + for line in f: + if any(n.lower() in line.lower() for n in needles): + hits.append(line.rstrip()) + if hits: + print("FILE", path, "hits", len(hits)) + for line in hits[-30:]: + print(line[:300]) + except Exception as e: + pass + +# journal for youtube/ffmpeg today morning +os.system("journalctl -u 'live*' --since '2026-06-24 05:00' --until '2026-06-24 09:30' 2>/dev/null | grep -iE 'douyin|288944|629587|source|room' | tail -40") +os.system("journalctl --since '2026-06-24 05:00' --until '2026-06-24 09:30' 2>/dev/null | grep -iE 'douyin|288944|629587|334176|youtube.py' | tail -40") + +# process runner / state +for p in [f"{BASE}/.process_runner/state.json", f"{BASE}/config/runtime-source.json"]: + if os.path.exists(p): + print("===", p, "===") + print(open(p, errors='replace').read()[:4000]) + +# current youtube child / source tracking files +for root, dirs, files in os.walk(f"{BASE}/config"): + for fn in files: + if any(x in fn.lower() for x in ("source", "current", "active", "runtime")): + fp = os.path.join(root, fn) + print("===", fp, "===") + print(open(fp, errors='replace').read()[:2000]) +''' + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _, o, e = c.exec_command(f"python3 - <<'PY'\n{REMOTE}\nPY", timeout=120, get_pty=True) + print((o.read() + e.read()).decode("utf-8", "replace")[:25000]) + c.close() + return 0 + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/query_host03_morning_logs2.py b/d2ypp2/tools/query_host03_morning_logs2.py new file mode 100644 index 0000000..807d688 --- /dev/null +++ b/d2ypp2/tools/query_host03_morning_logs2.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Find youtube.py log output and room at ~07:00 on host03.""" +from __future__ import annotations + +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" + +REMOTE = r''' +import os, glob, re, time +from datetime import datetime + +# find non-empty logs modified today +candidates = [] +for root in ["/opt/live/d2ypp", "/home/eric/d2ypp2-src", "/tmp", "/var/log"]: + for path in glob.glob(root + "/**/*", recursive=True): + try: + if not os.path.isfile(path): + continue + if os.path.getsize(path) == 0: + continue + mtime = os.path.getmtime(path) + if mtime < time.time() - 48*3600: + continue + if any(x in path.lower() for x in ["youtube", "ffmpeg", "streamget", "playurl", "pm2", "douyin", "record"]): + candidates.append((mtime, path, os.path.getsize(path))) + except Exception: + pass +candidates.sort(reverse=True) +print("=== recent log-like files ===") +for mtime, path, size in candidates[:40]: + print(datetime.fromtimestamp(mtime).isoformat(), size, path) + +# grep morning recordings in likely logs +patterns = ["正在录制", "录制 1 路", "YOUTUBE", "live.douyin.com/288944", "live.douyin.com/629587", "live.douyin.com/334176"] +for mtime, path, size in candidates[:25]: + if size > 50_000_000: + continue + try: + with open(path, "r", errors="replace") as f: + hits = [] + for line in f: + if "2026-06-24T0" in line or "2026-06-24 0" in line: + if any(p in line for p in patterns) or "live.douyin.com" in line: + if "06:" in line or "07:" in line or "05:" in line: + hits.append(line.rstrip()) + if hits: + print(f"\n=== {path} morning hits {len(hits)} ===") + for line in hits[-40:]: + print(line[:350]) + except Exception: + pass + +# systemd for youtube if any +os.system("systemctl list-units '*youtube*' '*live*' 2>/dev/null | head -20") +''' + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _, o, e = c.exec_command(f"python3 - <<'PY'\n{REMOTE}\nPY", timeout=180, get_pty=True) + print((o.read() + e.read()).decode("utf-8", "replace")[:30000]) + c.close() + return 0 + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/query_host03_opt_live.py b/d2ypp2/tools/query_host03_opt_live.py new file mode 100644 index 0000000..566fe18 --- /dev/null +++ b/d2ypp2/tools/query_host03_opt_live.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Query /opt/live/d2ypp on 10.88.0.3 for lane1 douyin source and history.""" +from __future__ import annotations + +import json +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +BASE = "/opt/live/d2ypp" +SRC = "/home/eric/d2ypp2-src" + + +def q(cmd: str, timeout: int = 120) -> str: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +CMDS = [ + ("date", "date; uptime"), + ("url_config_youtube", f"cat {BASE}/config/URL_config.youtube.ini 2>/dev/null; echo '---SRC---'; cat {SRC}/config/URL_config.youtube.ini 2>/dev/null"), + ("url_config_lane2", f"cat {BASE}/config/URL_config.youtube2__ch_mpykhmnj_lsrv7.ini 2>/dev/null"), + ( + "hub_sqlite", + f"sqlite3 {SRC}/config/hub_state.sqlite '.tables' 2>/dev/null; " + f"sqlite3 {SRC}/config/hub_state.sqlite \"SELECT key, substr(value,1,8000) FROM kv\" 2>/dev/null; " + f"sqlite3 {BASE}/config/hub_state.sqlite '.tables' 2>/dev/null; " + f"sqlite3 {BASE}/config/hub_state.sqlite \"SELECT key, substr(value,1,8000) FROM kv\" 2>/dev/null", + ), + ("pm2_opt", f"PM2_HOME={BASE}/.pm2 pm2 list 2>/dev/null; PM2_HOME={BASE}/.pm2 pm2 jlist 2>/dev/null | head -c 8000"), + ("logs_opt", f"find {BASE}/.pm2/logs -type f -printf '%T@ %TY-%Tm-%Td %TH:%TM %p %s\\n' 2>/dev/null | sort -nr | head -20"), + ("grep_douyin_opt", f"grep -hE 'live.douyin.com|source|room|title|start|stop' {BASE}/.pm2/logs/*.log 2>/dev/null | tail -100"), + ("youtube_live_store", f"find {BASE} {SRC} -name '*live*store*' -o -name '*youtube*event*' -o -name '*session*' 2>/dev/null | head -20"), + ("api_hub", "curl -sS -m 20 'http://127.0.0.1:8001/hub/dashboard' 2>/dev/null | head -c 12000"), + ("api_process", "curl -sS -m 20 'http://127.0.0.1:8001/process_monitor?family=youtube' 2>/dev/null"), + ("backup_urls", f"ls -lt {SRC}/backup_config/URL_config.youtube.ini_* 2>/dev/null | head -10; echo '---'; for f in $(ls -t {SRC}/backup_config/URL_config.youtube.ini_* 2>/dev/null | head -5); do echo \"=== $f ===\"; cat \"$f\"; done"), +] + + +def main() -> int: + for label, cmd in CMDS: + print(f"\n{'='*60}\n=== {label} ===\n{'='*60}") + try: + out = q(cmd) + if out.strip().startswith(("{", "[")): + try: + print(json.dumps(json.loads(out), ensure_ascii=False, indent=2)[:15000]) + continue + except Exception: + pass + print(out[:20000].encode("ascii", "backslashreplace").decode()) + except Exception as exc: + print(f"ERR: {exc}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/query_host03_recordings.py b/d2ypp2/tools/query_host03_recordings.py new file mode 100644 index 0000000..c784ecb --- /dev/null +++ b/d2ypp2/tools/query_host03_recordings.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +import paramiko, json + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" + +REMOTE = r''' +import os, glob, time, subprocess +from datetime import datetime + +def run(cmd): + return subprocess.check_output(cmd, shell=True, text=True, errors='replace') + +print(run("ps aux | grep youtube.py | grep -v grep")) +print(run("ps aux | grep 'ffmpeg.*rtmps' | grep -v grep")) + +# recording dirs +for base in ["/opt/live/d2ypp", "/home/eric/d2ypp2-src", "/home/eric"]: + for pat in ["**/download/**", "**/downloads/**", "**/录制/**", "**/*record*/*"]: + for path in glob.glob(base + "/" + pat, recursive=True)[:5]: + if os.path.isdir(path): + print("DIR", path, "files", len(os.listdir(path)[:200])) + +# find video files modified between 05:00-08:00 today +hits=[] +for root in ["/opt/live/d2ypp", "/home/eric"]: + for path in glob.glob(root + "/**/*", recursive=True): + try: + if not os.path.isfile(path): continue + if os.path.getsize(path) < 1000: continue + ext=os.path.splitext(path)[1].lower() + if ext not in ['.ts','.flv','.mp4','.mkv','.part']: continue + m=os.path.getmtime(path) + ts=datetime.fromtimestamp(m) + if ts.date().isoformat()=='2026-06-24' and 4 <= ts.hour <= 9: + hits.append((m, path, os.path.getsize(path))) + except: pass +hits.sort(reverse=True) +print('=== video files 04-09 today ===') +for m,p,s in hits[:30]: + print(datetime.fromtimestamp(m).isoformat(), s, p) + +# config.ini recording path +for cfg in ["/opt/live/d2ypp/config/config.ini", "/home/eric/d2ypp2-src/config/config.ini"]: + if os.path.exists(cfg): + print('===', cfg, '===') + print(open(cfg, errors='replace').read()[:2500]) + +# query sqlite for samples with payload containing douyin around morning - broader +import sqlite3 +conn=sqlite3.connect('/opt/live/d2ypp/config/hub_state.sqlite') +conn.row_factory=sqlite3.Row +rows=conn.execute( + "SELECT s.ts, s.payload_json, e.process, e.source_room_id " + "FROM youtube_live_samples s JOIN youtube_live_events e ON e.id=s.event_id " + "WHERE s.ts BETWEEN ? AND ? AND e.process='youtube' ORDER BY s.ts", + (time.time()-20*3600, time.time()-10*3600), +).fetchall() +print('samples 10-20h ago', len(rows)) +for r in rows[:20]: + print(datetime.fromtimestamp(r['ts']).isoformat(), r['source_room_id'], (r['payload_json'] or '')[:200]) +conn.close() +''' + +def main(): + c = paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _,o,e = c.exec_command(f"python3 - <<'PY'\n{REMOTE}\nPY", timeout=180, get_pty=True) + out = (o.read() + e.read()).decode("utf-8", "replace")[:25000] + import sys + sys.stdout.buffer.write(out.encode("utf-8", "replace") + b"\n") + c.close() + +if __name__ == '__main__': + main() diff --git a/d2ypp2/tools/query_host03_root_log_grep.py b/d2ypp2/tools/query_host03_root_log_grep.py new file mode 100644 index 0000000..c839e46 --- /dev/null +++ b/d2ypp2/tools/query_host03_root_log_grep.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" + +def main(): + c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + remote = r''' +LOG=/root/.pm2/logs/youtube-out.log +echo "=== 07:xx recording lines ===" +grep "正在录制 1 路" "$LOG" | grep "2026-06-24T07:" | tail -30 +echo "=== 2:0x duration lines today ===" +grep "正在录制 1 路" "$LOG" | grep "2026-06-24" | grep -E "原画 2:0[0-9]:|原画 2:1[0-9]:" | tail -40 +echo "=== around 2:05 exactly ===" +grep "正在录制 1 路" "$LOG" | grep -E "原画 2:05:|原画 2:04:|原画 2:06:" | tail -30 +echo "=== first 2:05 today ===" +grep "正在录制 1 路" "$LOG" | grep "2026-06-24" | grep "原画 2:05:" | head -5 +echo "=== last before 07:15 with 2h+ ===" +grep "正在录制 1 路" "$LOG" | grep "2026-06-24T07:1" | tail -10 +''' + _, o, e = c.exec_command( + f"echo {PASS} | sudo -S python3 - <<'PY'\n" + "import subprocess\n" + "LOG='/root/.pm2/logs/youtube-out.log'\n" + "def rg(pat, tail=30):\n" + " out=subprocess.check_output(f\"grep -F '{pat}' {LOG} | tail -{tail}\", shell=True, text=True, errors='replace')\n" + " print(out)\n" + "print('=== 07:xx recording ===')\n" + "rg('2026-06-24T07:')\n" + "print('=== 2:05 duration ===')\n" + "out=subprocess.check_output(\"grep '正在录制 1 路' /root/.pm2/logs/youtube-out.log | grep '原画 2:05:' | tail -20\", shell=True, text=True, errors='replace')\n" + "print(out)\n" + "print('=== 2:04-2:06 today ===')\n" + "out=subprocess.check_output(\"grep '正在录制 1 路' /root/.pm2/logs/youtube-out.log | grep '2026-06-24' | grep -E '原画 2:0[4-6]:' | tail -30\", shell=True, text=True, errors='replace')\n" + "print(out)\n" + "PY", + timeout=180, + get_pty=True, + ) + import sys; sys.stdout.buffer.write((o.read()+e.read())[:40000]) + c.close() + +if __name__=='__main__': main() diff --git a/d2ypp2/tools/query_host03_root_pm2_logs.py b/d2ypp2/tools/query_host03_root_pm2_logs.py new file mode 100644 index 0000000..0543c83 --- /dev/null +++ b/d2ypp2/tools/query_host03_root_pm2_logs.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +REMOTE = r''' +import subprocess, re, os + +cmds = [ + "PM2_HOME=/root/.pm2 pm2 list 2>/dev/null", + "ls -la /root/.pm2/logs/ 2>/dev/null | head -30", + "ls -la /opt/live/d2ypp/.pm2/logs/ 2>/dev/null", + "wc -c /root/.pm2/logs/youtube-out.log /opt/live/d2ypp/.pm2/pm2.log 2>/dev/null", + "grep -E '正在录制 1 路.*原画 2:0|正在录制 1 路.*原画 2:1|正在录制 1 路.*原画 2:05' /root/.pm2/logs/youtube-out.log 2>/dev/null | tail -30", + "grep '2026-06-24T07:' /root/.pm2/logs/youtube-out.log 2>/dev/null | grep '正在录制 1 路' | tail -20", + "grep '2026-06-24T06:' /root/.pm2/logs/youtube-out.log 2>/dev/null | grep '正在录制 1 路' | tail -20", + "grep '2026-06-24T05:' /root/.pm2/logs/youtube-out.log 2>/dev/null | grep '正在录制 1 路' | tail -20", +] +for cmd in cmds: + print('===', cmd[:100], '===') + try: + out=subprocess.check_output(cmd, shell=True, text=True, errors='replace') + print(out[:8000]) + except Exception as e: + print('ERR', e) +''' + +def main(): + c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _,o,e=c.exec_command(f"sudo -S python3 - <<'PY'\n{REMOTE}\nPY", timeout=180, get_pty=True) + # send password for sudo + stdin=o.channel.makefile('wb', -1) + # actually password via echo + c.close() + c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _,o,e=c.exec_command(f"echo Xiao4669805 | sudo -S bash -lc \"{REMOTE.replace(chr(10),' ')[:10]}\"", timeout=5) + # simpler: run as eric with direct paths if readable + c.close() + c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + cmd = r'''bash -lc ' +for f in /root/.pm2/logs/youtube-out.log /root/.pm2/logs/youtube-error.log; do + echo FILE $f; ls -la $f 2>/dev/null || echo missing +done +if [ -r /root/.pm2/logs/youtube-out.log ]; then + grep "正在录制 1 路" /root/.pm2/logs/youtube-out.log | grep "2026-06-24T07" | tail -10 + grep "正在录制 1 路" /root/.pm2/logs/youtube-out.log | grep "原画 2:0" | tail -15 +else + echo cannot read root pm2 logs + PM2_HOME=/root/.pm2 sudo -S pm2 list 2>/dev/null | head -10 +fi +' ''' + _,o,e=c.exec_command(f"echo Xiao4669805 | sudo -S {cmd}", timeout=180, get_pty=True) + import sys; sys.stdout.buffer.write((o.read()+e.read())[:30000]) + c.close() +if __name__=='__main__': main() diff --git a/d2ypp2/tools/query_host03_runtime.py b/d2ypp2/tools/query_host03_runtime.py new file mode 100644 index 0000000..43d6cd4 --- /dev/null +++ b/d2ypp2/tools/query_host03_runtime.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Resolve current ffmpeg stream to douyin room; check runtime status files.""" +from __future__ import annotations + +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +REMOTE = r''' +import os, json, subprocess, re, sys +sys.path.insert(0, "/opt/live/d2ypp") +os.chdir("/opt/live/d2ypp") + +def run(cmd): + return subprocess.check_output(cmd, shell=True, text=True, errors='replace') + +# runtime status from API internals +import urllib.request +for url in [ + "http://127.0.0.1:8001/process_monitor?family=youtube", + "http://127.0.0.1:8001/status?process=youtube", + "http://127.0.0.1:8001/process_status?process=youtube", +]: + try: + print("===", url, "===") + print(urllib.request.urlopen(url, timeout=15).read().decode()[:4000]) + except Exception as e: + print("ERR", e) + +# find runtime json under config/data +for root, dirs, files in os.walk("/opt/live/d2ypp"): + for fn in files: + if fn.endswith('.json') and any(x in fn.lower() for x in ['runtime','status','source','relay','ffmpeg']): + fp=os.path.join(root, fn) + print('===', fp, '===') + print(open(fp, errors='replace').read()[:3000]) + +# try resolve room from pull url anchor +ff = run("ps aux | grep 'ffmpeg.*rtmps' | grep -v grep | head -1") +print('ffmpeg', ff[:500]) +m = re.search(r'unique_id=([^&\s]+)', ff) +if m: + print('unique_id', m.group(1)) + +# grep youtube.py status file +for p in ["/opt/live/d2ypp/.runtime/youtube.json", "/opt/live/d2ypp/runtime/youtube.json", "/tmp/youtube_status.json"]: + if os.path.exists(p): + print('===', p, '===') + print(open(p).read()[:4000]) + +# list .runtime / .process_runner +for d in ["/opt/live/d2ypp/.runtime", "/opt/live/d2ypp/.process_runner", "/opt/live/d2ypp/data"]: + if os.path.isdir(d): + print('DIR', d, os.listdir(d)) +''' + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _, o, e = c.exec_command(f"python3 - <<'PY'\n{REMOTE}\nPY", timeout=90, get_pty=True) + import sys + sys.stdout.buffer.write((o.read() + e.read())[:25000]) + c.close() + +if __name__ == "__main__": + main() diff --git a/d2ypp2/tools/query_host03_samples_today.py b/d2ypp2/tools/query_host03_samples_today.py new file mode 100644 index 0000000..5b8de6c --- /dev/null +++ b/d2ypp2/tools/query_host03_samples_today.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +REMOTE = r''' +import sqlite3, json, time, re +from datetime import datetime + +conn=sqlite3.connect("/opt/live/d2ypp/config/hub_state.sqlite") +conn.row_factory=sqlite3.Row +now=time.time() +# all samples today for youtube process +start=now-24*3600 +rows=conn.execute( + "SELECT s.id, s.ts, s.source, s.payload_json, e.id as eid, e.source_room_id " + "FROM youtube_live_samples s JOIN youtube_live_events e ON e.id=s.event_id " + "WHERE e.process='youtube' AND s.ts >= ? ORDER BY s.ts", + (start,), +).fetchall() +print('samples today', len(rows)) +for r in rows: + payload = r['payload_json'] or '' + if len(payload) < 5: + continue + ts = datetime.fromtimestamp(r['ts']).isoformat() + # look for recording duration in payload + if '正在录制' in payload or '原画 2:' in payload or '原画 1:' in payload or 'recent_log' in payload: + print('---', ts, 'event', r['eid'], 'room', r['source_room_id'], '---') + try: + p=json.loads(payload) + log=p.get('recent_log','') + for line in log.split('\n'): + if '正在录制' in line: + print(line[:220]) + except Exception: + print(payload[:300]) + +# grep ingest payloads around 7am in all samples +print('\n=== samples 06:00-08:30 with recording line ===') +t0=datetime(2026,6,24,6,0,0).timestamp() +t1=datetime(2026,6,24,8,30,0).timestamp() +rows2=conn.execute( + "SELECT s.ts, s.payload_json FROM youtube_live_samples s " + "JOIN youtube_live_events e ON e.id=s.event_id WHERE e.process='youtube' AND s.ts BETWEEN ? AND ?", + (t0,t1), +).fetchall() +print('count', len(rows2)) +for r in rows2: + p=r['payload_json'] or '' + if '正在录制' in p: + ts=datetime.fromtimestamp(r['ts']).isoformat() + m=re.search(r'正在录制 1 路: ([^\[]+)\[原画 ([0-9:]+)\]', p) + if m: + print(ts, m.group(1).strip(), m.group(2)) + +# update event 67 current fields +r=conn.execute("SELECT source_room_id, source_url, snapshot_json, duration_seconds, started_at FROM youtube_live_events WHERE id=67").fetchone() +print('\nEVENT67', dict(r)) +conn.close() + +# pull status log lines with 2:0x duration from ring if stored anywhere +import urllib.request +st=json.loads(urllib.request.urlopen('http://127.0.0.1:8001/status?process=youtube', timeout=20).read()) +log=st.get('recent_log','') +for line in log.split('\n'): + if '正在录制' in line and '原画 2:' in line: + print('NOW2H', line) +''' + +def main(): + c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _,o,e=c.exec_command(f"python3 - <<'PY'\n{REMOTE}\nPY", timeout=90, get_pty=True) + import sys; sys.stdout.buffer.write((o.read()+e.read())[:40000]) + c.close() +if __name__=='__main__': main() diff --git a/d2ypp2/tools/query_host03_snapshot_search.py b/d2ypp2/tools/query_host03_snapshot_search.py new file mode 100644 index 0000000..fc6fec1 --- /dev/null +++ b/d2ypp2/tools/query_host03_snapshot_search.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +import paramiko, json + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +REMOTE = r''' +import sqlite3, json, re +from datetime import datetime + +conn=sqlite3.connect("/opt/live/d2ypp/config/hub_state.sqlite") +conn.row_factory=sqlite3.Row + +# search snapshots for morning recording lines +rows=conn.execute("SELECT id, process, source_room_id, started_at, ended_at, duration_seconds, snapshot_json FROM youtube_live_events WHERE process='youtube' ORDER BY id DESC LIMIT 10").fetchall() +for r in rows: + snap=r['snapshot_json'] or '' + if '2026-06-24' in snap or r['id']==67: + print('EVENT', r['id'], 'room', r['source_room_id'], 'dur', r['duration_seconds']) + # extract recording lines + for line in snap.split('\\n'): + if '正在录制' in line or '录制 1 路' in line or '2026-06-24T0' in line: + if any(h in line for h in ['05:','06:','07:','08:']): + print(' ', line[:250]) + +# search all snapshots for 2:05 or 2:04 or 2:06 duration patterns +print('\n=== snapshot search 2:0x duration ===') +rows2=conn.execute("SELECT id, process, source_room_id, snapshot_json FROM youtube_live_events WHERE snapshot_json LIKE '%2:0%' OR snapshot_json LIKE '%2:1%' OR snapshot_json LIKE '%2:05%'").fetchall() +for r in rows2: + snap=r['snapshot_json'] + for pat in [r'\[原画 2:0[0-9]:[0-9]{2}\]', r'\[原画 2:1[0-9]:[0-9]{2}\]', r'2:05:', r'2:04:', r'2:06:']: + m=re.search(pat, snap) + if m: + print('id', r['id'], 'room', r['source_room_id'], 'match', m.group(0)) + # context + idx=snap.find(m.group(0)) + print(snap[max(0,idx-120):idx+120]) + +# fetch current status recent_log recording lines +import urllib.request +st=json.loads(urllib.request.urlopen('http://127.0.0.1:8001/status?process=youtube', timeout=20).read()) +log=st.get('recent_log','') +print('\n=== current recording lines ===') +for line in log.split('\n'): + if '正在录制' in line or '录制 1 路' in line or '原画' in line: + print(line[:200]) + +conn.close() +''' + +def main(): + c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _,o,e=c.exec_command(f"python3 - <<'PY'\n{REMOTE}\nPY", timeout=90, get_pty=True) + import sys; sys.stdout.buffer.write((o.read()+e.read())[:30000]) + c.close() +if __name__=='__main__': main() diff --git a/d2ypp2/tools/query_host03_youtube_events.py b/d2ypp2/tools/query_host03_youtube_events.py new file mode 100644 index 0000000..41b3a28 --- /dev/null +++ b/d2ypp2/tools/query_host03_youtube_events.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Query youtube_live_events on 10.88.0.3 for lane1 ~12h ago session.""" +from __future__ import annotations + +import json +import time +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" + +REMOTE_PY = r''' +import sqlite3, json, time, os +from datetime import datetime + +paths = [ + "/opt/live/d2ypp/config/hub_state.sqlite", + "/home/eric/d2ypp2-src/config/hub_state.sqlite", +] +now = time.time() +print("now", now, datetime.fromtimestamp(now).isoformat()) +print("12h_ago", now - 12*3600, datetime.fromtimestamp(now - 12*3600).isoformat()) + +for p in paths: + if not os.path.exists(p): + print("missing", p) + continue + print("\nDB", p, "size", os.path.getsize(p)) + conn = sqlite3.connect(p) + conn.row_factory = sqlite3.Row + tables = [r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()] + print("tables", tables) + if "youtube_live_events" not in tables: + conn.close() + continue + cnt = conn.execute("SELECT COUNT(*) FROM youtube_live_events").fetchone()[0] + print("event_count", cnt) + rows = conn.execute( + """SELECT id, process, channel_name, source_url, source_room_id, source_title, + status, started_at, ended_at, duration_seconds, last_seen_at + FROM youtube_live_events + ORDER BY started_at DESC LIMIT 30""" + ).fetchall() + for r in rows: + d = dict(r) + for k in ("started_at", "ended_at", "last_seen_at"): + if d.get(k): + d[k + "_iso"] = datetime.fromtimestamp(float(d[k])).isoformat() + print(json.dumps(d, ensure_ascii=False)) + + # events around 12h ago with duration ~125 min (7500s) + target = now - 12*3600 + rows2 = conn.execute( + """SELECT id, process, channel_name, source_url, source_room_id, source_title, + status, started_at, ended_at, duration_seconds + FROM youtube_live_events + WHERE started_at BETWEEN ? AND ? + OR (ended_at BETWEEN ? AND ?) + OR (started_at < ? AND (ended_at IS NULL OR ended_at > ?)) + ORDER BY started_at DESC""", + (target - 4*3600, target + 4*3600, target - 4*3600, target + 4*3600, target, target), + ).fetchall() + print("\n--- events near 12h ago ---") + for r in rows2: + d = dict(r) + for k in ("started_at", "ended_at"): + if d.get(k): + d[k + "_iso"] = datetime.fromtimestamp(float(d[k])).isoformat() + print(json.dumps(d, ensure_ascii=False)) + + rows3 = conn.execute( + """SELECT id, process, source_url, source_title, duration_seconds, started_at, ended_at + FROM youtube_live_events + WHERE duration_seconds BETWEEN 7000 AND 8000 + ORDER BY started_at DESC LIMIT 20""" + ).fetchall() + print("\n--- duration 7000-8000s (~2h) ---") + for r in rows3: + d = dict(r) + for k in ("started_at", "ended_at"): + if d.get(k): + d[k + "_iso"] = datetime.fromtimestamp(float(d[k])).isoformat() + print(json.dumps(d, ensure_ascii=False)) + + if "kv" in tables: + for row in conn.execute("SELECT key FROM kv").fetchall(): + print("kv_key", row[0]) + r = conn.execute("SELECT value FROM kv WHERE key='youtube_pro_channels_v1'").fetchone() + if r: + print("youtube_pro_channels", r[0][:3000]) + conn.close() +''' + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=15) + _, o, e = c.exec_command(f"python3 - <<'PY'\n{REMOTE_PY}\nPY", timeout=90, get_pty=True) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + print(out) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/read_host03_youtube_log.py b/d2ypp2/tools/read_host03_youtube_log.py new file mode 100644 index 0000000..6ea2776 --- /dev/null +++ b/d2ypp2/tools/read_host03_youtube_log.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +import paramiko, sys, base64 + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +REMOTE = r''' +import re +path = "/root/.pm2/logs/youtube-out.log" +with open(path, "r", errors="replace") as f: + lines = f.readlines() + +def show(title, pred, tail=30): + hits = [ln.rstrip() for ln in lines if pred(ln.rstrip())] + print(f"\n=== {title} ({len(hits)} hits) ===") + for ln in hits[-tail:]: + print(ln[:300]) + +show("2:05 duration", lambda ln: "正在录制 1 路" in ln and "原画 2:05:" in ln, 25) +show("07:xx recording", lambda ln: "正在录制 1 路" in ln and "2026-06-24T07:" in ln, 30) +show("06:xx with 2h+", lambda ln: "正在录制 1 路" in ln and "2026-06-24T06:" in ln and "原画 2:" in ln, 25) +show("05:xx with 2h+", lambda ln: "正在录制 1 路" in ln and "2026-06-24T05:" in ln and "原画 2:" in ln, 25) + +best = [] +for ln in lines: + if "正在录制 1 路" not in ln or "2026-06-24T07:1" not in ln: + continue + m = re.search(r"正在录制 1 路: ([^\[]+)\[原画 ([0-9:]+)\]", ln) + if m: + best.append((m.group(2), m.group(1).strip())) +print("\n=== 07:1x recording names ===") +for dur, name in best[-15:]: + print(dur, name[:80]) +''' +b64 = base64.b64encode(REMOTE.encode()).decode() +cmd = f"echo {PASS} | sudo -S python3 -c \"import base64; exec(base64.b64decode('{b64}').decode())\"" + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect(HOST, username=USER, password=PASS, timeout=15) +_, o, e = c.exec_command(cmd, timeout=180, get_pty=True) +out = (o.read() + e.read()).decode("utf-8", "replace") +c.close() +sys.stdout.buffer.write(out.encode("utf-8", "replace")) diff --git a/d2ypp2/tools/read_host03_youtube_log_probe.py b/d2ypp2/tools/read_host03_youtube_log_probe.py new file mode 100644 index 0000000..917f6b1 --- /dev/null +++ b/d2ypp2/tools/read_host03_youtube_log_probe.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +import paramiko, sys, base64 + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +REMOTE = r''' +path = "/root/.pm2/logs/youtube-out.log" +with open(path, "r", errors="replace") as f: + lines = f.readlines() +print('total lines', len(lines)) +# sample lines with 录制 +hits=[ln for ln in lines if '录制' in ln] +print('lines with 录制', len(hits)) +for ln in hits[:5]: + print('SAMPLE', repr(ln[:200])) +for ln in hits[-5:]: + print('TAIL', repr(ln[:200])) +# unique date prefixes today +from collections import Counter +c=Counter() +for ln in lines: + if ln.startswith('2026-06-24'): + c[ln[:13]] += 1 +print('date prefixes', dict(c)) +# any line with 2:05 +h2=[ln for ln in lines if '2:05' in ln and '录制' in ln] +print('2:05 recording lines', len(h2)) +for ln in h2[-10:]: + print(ln[:250]) +# lines at hour 07 +h7=[ln for ln in lines if '2026-06-24' in ln and ('T07:' in ln or ' 07:' in ln) and '录制' in ln] +print('hour07 recording', len(h7)) +for ln in h7[-15:]: + print(ln[:250]) +''' +b64 = base64.b64encode(REMOTE.encode()).decode() +cmd = f"echo {PASS} | sudo -S python3 -c \"import base64; exec(base64.b64decode('{b64}').decode())\"" +c = paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect(HOST, username=USER, password=PASS, timeout=15) +_, o, e = c.exec_command(cmd, timeout=180, get_pty=True) +out = (o.read() + e.read()).decode("utf-8", "replace") +c.close() +sys.stdout.buffer.write(out.encode("utf-8", "replace")) diff --git a/d2ypp2/tools/restart_all_youtube_lanes.py b/d2ypp2/tools/restart_all_youtube_lanes.py new file mode 100644 index 0000000..2f3b6bd --- /dev/null +++ b/d2ypp2/tools/restart_all_youtube_lanes.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Restart all youtube lanes on 3 hosts to load new youtube.py code.""" +from __future__ import annotations + +import json +import paramiko +import sys +import time + +if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8", errors="backslashreplace") + +HOSTS = [ + ("192.168.2.237", "eric", "4669805"), + ("10.88.0.3", "eric", "Xiao4669805"), + ("10.88.0.5", "eric", "4669805"), +] + + +def run(ssh, cmd: str, timeout: int = 180) -> str: + _, o, e = ssh.exec_command(cmd, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace").strip() + + +def fetch_dashboard(ssh, pw: str) -> dict | None: + raw = run(ssh, "curl -sS -m 20 http://127.0.0.1:8001/hub/dashboard") + try: + return json.loads(raw) + except json.JSONDecodeError: + print(" dashboard unavailable, restarting live-console...") + print(run(ssh, f"echo '{pw}' | sudo -S -p '' systemctl restart live-console.service", timeout=120)) + time.sleep(6) + raw = run(ssh, "curl -sS -m 20 http://127.0.0.1:8001/hub/dashboard") + try: + return json.loads(raw) + except json.JSONDecodeError: + print(" dashboard still unavailable:", raw[:200]) + return None + + +def youtube_rows(dash: dict) -> list[dict]: + rows = [] + for p in dash.get("live", {}).get("processes", []): + name = str(p.get("pm2") or "").strip() + if name.startswith("youtube"): + rows.append(p) + return rows + + +def main() -> None: + for host, user, pw in HOSTS: + print("=" * 72) + print(host) + print("=" * 72) + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + try: + ssh.connect(host, username=user, password=pw, timeout=25) + except Exception as exc: + print("SSH FAIL:", exc) + continue + + rtmps = run(ssh, "pgrep -af ffmpeg 2>/dev/null | grep rtmps | grep -v pgrep || true") + print("rtmps before:", len(rtmps.splitlines()) if rtmps else 0) + + dash = fetch_dashboard(ssh, pw) + if dash is None: + ssh.close() + continue + + procs = youtube_rows(dash) + print("youtube lanes:", len(procs)) + for row in procs: + print( + f" {row.get('pm2')}: biz={row.get('business_status')} " + f"push={row.get('is_pushing')} status={row.get('process_status')}" + ) + + for row in procs: + proc = str(row.get("pm2") or "") + if not proc: + continue + out = run( + ssh, + "curl -sS -m 120 -X POST 'http://127.0.0.1:8001/restart' " + "-H 'Content-Type: application/json' " + f"-d '{{\"process\":\"{proc}\"}}'", + timeout=150, + ) + print(f"restart {proc}: {out[:220]!r}") + + time.sleep(12) + dash2 = fetch_dashboard(ssh, pw) + if dash2: + for row in youtube_rows(dash2): + print( + f" after {row.get('pm2')}: biz={row.get('business_status')} " + f"push={row.get('is_pushing')} status={row.get('process_status')}" + ) + + rtmps2 = run(ssh, "pgrep -af ffmpeg 2>/dev/null | grep rtmps | grep -v pgrep || true") + print("rtmps after:", len(rtmps2.splitlines()) if rtmps2 else 0) + ssh.close() + + print("DONE") + + +if __name__ == "__main__": + main() diff --git a/d2ypp2/tools/run_stop_optional_hosts.py b/d2ypp2/tools/run_stop_optional_hosts.py new file mode 100644 index 0000000..7a94795 --- /dev/null +++ b/d2ypp2/tools/run_stop_optional_hosts.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Upload stop script and run on streaming hosts.""" +from __future__ import annotations + +import io +import paramiko +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +HOSTS = [ + ("192.168.2.237", "eric", "4669805", "/home/eric/d2ypp2-src"), + ("192.168.2.101", "eric", "4669805", "/opt/live/d2ypp"), +] +UPLOAD = [ + "scripts/linux/stop_optional_hub_services.sh", + "scripts/linux/service_ctl.sh", + "scripts/linux/lib/common.sh", +] + +STOP_INLINE = """#!/usr/bin/env bash +set -e +PAT='live-frigate|live-homeassistant|live-openclaw|live-srs|live-mitmproxy|live-code-server|live-homepage|live-filebrowser|live-uptime-kuma|live-ntfy|redroid' +for u in live-redroid-host live-frigate-usb-watch live-android-panel live-webtty live-pulseaudio; do + systemctl disable --now "$u.service" 2>/dev/null || true +done +mapfile -t names < <(docker ps --format '{{.Names}}' 2>/dev/null | grep -E "$PAT" || true) +if [ "${#names[@]}" -gt 0 ]; then docker stop "${names[@]}" 2>/dev/null || true; fi +STACK_ENV='__BASE__/config/system-stack.env' +mkdir -p "$(dirname "$STACK_ENV")" +touch "$STACK_ENV" +for k in ENABLE_REDROID ENABLE_FRIGATE FRIGATE_USB_AUTOSTART ENABLE_HOMEASSISTANT HOMEASSISTANT_AUTOSTART ENABLE_OPENCLAW ENABLE_SRS ENABLE_MITMPROXY ENABLE_VSCODE_SERVER ENABLE_HOMEPAGE ENABLE_FILEBROWSER ENABLE_UPTIME_KUMA ENABLE_NTFY ENABLE_ANDROID_PANEL ENABLE_WEBTTY ENABLE_PULSEAUDIO; do + if grep -q "^${k}=" "$STACK_ENV" 2>/dev/null; then sed -i "s/^${k}=.*/${k}=0/" "$STACK_ENV"; else echo "${k}=0" >>"$STACK_ENV"; fi +done +echo inline-stop-ok +""" + + +def put_lf(sftp, local: Path, remote: str) -> None: + data = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + sftp.putfo(io.BytesIO(data), remote) + + +for host, user, pw, base in HOSTS: + print(f"\n{'='*70}\n{host} ({base})\n{'='*70}") + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(host, username=user, password=pw, timeout=25) + sftp = ssh.open_sftp() + reinstall = [] + for rel in UPLOAD: + local = ROOT / rel + tmp = f"/tmp/_deploy_{rel.replace('/', '_')}" + dest = f"{base}/{rel.replace(chr(92), '/')}" + put_lf(sftp, local, tmp) + mode = "0755" if rel.endswith(".sh") else "0644" + reinstall.append(f"install -m {mode} {tmp} {dest}") + print(f"staged {rel}") + sftp.close() + install = " && ".join(reinstall) + _, o, e = ssh.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc '{install}'", timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")[:300]) + inline_path = "/tmp/stop_optional_inline.sh" + sftp2 = ssh.open_sftp() + sftp2.putfo(io.BytesIO(STOP_INLINE.replace("__BASE__", base).encode("utf-8")), inline_path) + sftp2.chmod(inline_path, 0o755) + sftp2.close() + _, o, e = ssh.exec_command(f"echo '{pw}' | sudo -S -p '' bash {inline_path}", timeout=300) + print((o.read() + e.read()).decode("utf-8", "replace")) + _, o, e = ssh.exec_command( + f"echo '{pw}' | sudo -S -p '' bash {base}/scripts/linux/stop_optional_hub_services.sh", + timeout=300, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + _, o2, _ = ssh.exec_command( + f"echo '{pw}' | sudo -S -p '' bash -lc 'docker ps --format \"{{{{.Names}}}}\\t{{{{.Status}}}}\" | sort; echo ---; uptime; curl -sf -m 5 http://127.0.0.1:8001/health'", + timeout=60, + ) + print((o2.read()).decode("utf-8", "replace")) + ssh.close() diff --git a/d2ypp2/tools/upload_console_out_host03.py b/d2ypp2/tools/upload_console_out_host03.py new file mode 100644 index 0000000..bdedca4 --- /dev/null +++ b/d2ypp2/tools/upload_console_out_host03.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Upload web-console/out to the correct path on host03 and verify.""" +from __future__ import annotations + +import posixpath +import sys +from pathlib import Path + +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" +BASE = "/opt/live/d2ypp" +OUT = Path(__file__).resolve().parent.parent / "web-console" / "out" + + +def mkdir_p(sftp: paramiko.SFTPClient, remote_dir: str) -> None: + remote_dir = remote_dir.replace("\\", "/").rstrip("/") + if not remote_dir or remote_dir == "/": + return + cur = "" + for part in [p for p in remote_dir.split("/") if p]: + cur = f"{cur}/{part}" if cur else f"/{part}" + try: + sftp.stat(cur) + except OSError: + try: + sftp.mkdir(cur) + except OSError: + pass + + +def put_tree(sftp: paramiko.SFTPClient, local_dir: Path, remote_dir: str) -> int: + count = 0 + for path in sorted(local_dir.rglob("*")): + if not path.is_file(): + continue + rel = path.relative_to(local_dir).as_posix() + remote = posixpath.join(remote_dir, rel) + mkdir_p(sftp, posixpath.dirname(remote)) + sftp.put(str(path), remote) + count += 1 + return count + + +def run(client: paramiko.SSHClient, cmd: str, timeout: int = 120) -> str: + _, stdout, stderr = client.exec_command(f"export LC_ALL=C.UTF-8; {cmd}", timeout=timeout) + return (stdout.read() + stderr.read()).decode("utf-8", "replace") + + +def safe_print(text: str) -> None: + try: + print(text) + except UnicodeEncodeError: + sys.stdout.buffer.write(text.encode("utf-8", errors="replace") + b"\n") + + +def main() -> int: + if not (OUT / "index.html").is_file(): + raise SystemExit("missing local web-console/out — run: cd web-console && pnpm run build") + + local_index = (OUT / "index.html").read_text(encoding="utf-8", errors="replace") + local_chunk = "371" if "371-" in local_index else "unknown" + safe_print(f"local index references chunk family: {local_chunk}") + + client = paramiko.SSHClient() + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.connect(HOST, username=USER, password=PASS, timeout=20) + sftp = client.open_sftp() + + remote_out = f"{BASE}/web-console/out" + uploaded = put_tree(sftp, OUT, remote_out) + safe_print(f"uploaded {uploaded} files -> {remote_out}") + + sftp.close() + + verify_cmds = [ + f"grep -o 'page-[a-z0-9]*\\.js' {remote_out}/index.html | head -1", + f"grep -o '371-[a-z0-9]*\\.js' {remote_out}/index.html | head -1", + f"grep -o '904-[a-z0-9]*\\.js' {remote_out}/index.html | head -1", + "curl -sS http://127.0.0.1:8001/ | grep -o '371-[a-z0-9]*\\.js\\|904-[a-z0-9]*\\.js' | head -3", + f"echo {PASS!r} | sudo -S -p '' systemctl restart live-console.service", + "sleep 6", + "curl -sf http://127.0.0.1:8001/health", + "curl -sS http://127.0.0.1:8001/ | grep -o '371-[a-z0-9]*\\.js\\|904-[a-z0-9]*\\.js' | head -3", + ] + for cmd in verify_cmds: + out = run(client, cmd, timeout=180) + safe_print(f"\n$ {cmd}\n{out.strip()[:500]}") + + client.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/verify_relay_log_host03.py b/d2ypp2/tools/verify_relay_log_host03.py new file mode 100644 index 0000000..eff90a4 --- /dev/null +++ b/d2ypp2/tools/verify_relay_log_host03.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Verify and recover live-console on 10.88.0.3 after relay log deploy.""" +from __future__ import annotations + +import sys + +import paramiko + +HOST, USER, PASS = "10.88.0.3", "eric", "Xiao4669805" + + +def run(c: paramiko.SSHClient, cmd: str, timeout: int = 120) -> tuple[int, str]: + _, o, e = c.exec_command("export LC_ALL=C.UTF-8 LANG=C.UTF-8; " + cmd, timeout=timeout) + out = (o.read() + e.read()).decode("utf-8", "replace") + return o.channel.recv_exit_status(), out + + +def safe_print(text: str) -> None: + try: + print(text) + except UnicodeEncodeError: + sys.stdout.buffer.write(text.encode("utf-8", errors="replace") + b"\n") + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=20) + + steps = [ + "systemctl is-active live-console.service 2>&1; systemctl status live-console.service --no-pager -n 20 2>&1", + f"echo {PASS!r} | sudo -S -p '' systemctl reset-failed live-console.service 2>/dev/null; " + f"echo {PASS!r} | sudo -S -p '' systemctl start live-console.service; sleep 8; " + "systemctl is-active live-console.service 2>&1", + "for i in 1 2 3 4 5 6 7 8 9 10; do " + "curl -sf -m 4 http://127.0.0.1:8001/health >/dev/null 2>&1 && echo health_ok && break; " + "sleep 3; done", + "curl -sS -m 10 -o /dev/null -w 'relay_log_page=%{http_code}\\n' http://127.0.0.1:8001/youtube-relay-log", + "curl -sS -m 10 'http://127.0.0.1:8001/hub/youtube/relay/sessions?limit=2' 2>&1 | head -c 800", + "journalctl -u live-console.service -n 30 --no-pager 2>&1", + ] + for step in steps: + code, out = run(c, step, timeout=180) + safe_print(f"\n=== exit={code} ===\n{out[:2500]}") + + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/web-console/app/youtube-relay-log/page.tsx b/d2ypp2/web-console/app/youtube-relay-log/page.tsx new file mode 100644 index 0000000..d6ae037 --- /dev/null +++ b/d2ypp2/web-console/app/youtube-relay-log/page.tsx @@ -0,0 +1,3 @@ +"use client"; + +export { default } from "@/components/live-product/LiveYoutubeRelayLogView"; diff --git a/d2ypp2/web-console/components/live-product/LiveControlApp.tsx b/d2ypp2/web-console/components/live-product/LiveControlApp.tsx index b1bef9e..c42c3b2 100644 --- a/d2ypp2/web-console/components/live-product/LiveControlApp.tsx +++ b/d2ypp2/web-console/components/live-product/LiveControlApp.tsx @@ -80,6 +80,7 @@ function initialViewKey(): ViewKey { const requested = new URLSearchParams(window.location.search).get("view"); if (isViewKey(requested)) return requested; if (window.location.pathname.replace(/\/$/, "") === "/youtube-events") return "live_youtube"; + if (window.location.pathname.replace(/\/$/, "") === "/youtube-relay-log") return "live_youtube"; return "dashboard"; } @@ -1705,7 +1706,7 @@ export default function LiveControlApp() { liveProcesses={processRows.length ? processRows : (dash?.live?.processes ?? [])} notify={notify} quickLinks={ql} - onRefresh={() => refreshDashboard()} + onRefresh={() => void Promise.all([refreshDashboard(), refreshProcessMonitor()])} onNavigate={(target: PortalNavTarget) => setView(target)} /> ) : null} diff --git a/d2ypp2/web-console/components/live-product/LiveProcessLiveLogCard.tsx b/d2ypp2/web-console/components/live-product/LiveProcessLiveLogCard.tsx index da7a3fd..6d97a95 100644 --- a/d2ypp2/web-console/components/live-product/LiveProcessLiveLogCard.tsx +++ b/d2ypp2/web-console/components/live-product/LiveProcessLiveLogCard.tsx @@ -85,6 +85,8 @@ type Props = { monitorRow?: MonitorRowHint; /** Pro 线路名:推流中时固定显示频道名 */ preferredTitle?: string; + /** 隐藏进程/业务状态、转推指标、源站摘要等概览区,仅保留日志输出 */ + hideStatusOverview?: boolean; }; function businessLine(t: TFn, raw: string | undefined, note: string | undefined): string { @@ -162,6 +164,7 @@ export function LiveProcessLiveLogCard({ refreshToken = 0, monitorRow, preferredTitle, + hideStatusOverview = false, }: Props) { const [processStatus, setProcessStatus] = useState(""); const [recentLog, setRecentLog] = useState(""); @@ -452,7 +455,7 @@ export function LiveProcessLiveLogCard({

{t("当前直播日志", "Live process log")}

- {pushingNow ? ( + {pushingNow && !hideStatusOverview ? ( @@ -492,6 +495,7 @@ export function LiveProcessLiveLogCard({
+ {!hideStatusOverview ? (
@@ -646,6 +650,7 @@ export function LiveProcessLiveLogCard({

)}
+ ) : null} {processStatus !== "not_found" && processStatus !== "invalid" ? (
diff --git a/d2ypp2/web-console/components/live-product/LiveYoutubeRelayLogView.tsx b/d2ypp2/web-console/components/live-product/LiveYoutubeRelayLogView.tsx new file mode 100644 index 0000000..d41d00e --- /dev/null +++ b/d2ypp2/web-console/components/live-product/LiveYoutubeRelayLogView.tsx @@ -0,0 +1,445 @@ +"use client"; + +import { ExternalLink, Loader2, RefreshCw, Search } from "lucide-react"; +import { useCallback, useEffect, useMemo, useState } from "react"; + +import { fetchJsonResponse } from "@/lib/fetchJson"; + +type Lang = "zh" | "en"; + +type RelaySession = { + id: number; + session_uuid?: string; + process?: string; + channel_name?: string; + anchor_name?: string; + source_url?: string; + source_room_id?: string; + stream_title?: string; + youtube_key_suffix?: string; + started_at?: number; + ended_at?: number | null; + duration_seconds?: number; + push_date?: string; + cover_url?: string; + status?: string; + end_reason?: string; + metadata?: Record; +}; + +function tr(lang: Lang, zh: string, en: string) { + return lang === "zh" ? zh : en; +} + +function fmtDuration(seconds: number | null | undefined, lang: Lang): string { + const total = Math.max(0, Math.floor(Number(seconds) || 0)); + const h = Math.floor(total / 3600); + const m = Math.floor((total % 3600) / 60); + const s = total % 60; + if (h > 0) return `${h}${tr(lang, "小时", "h")}${m}${tr(lang, "分", "m")}${s}${tr(lang, "秒", "s")}`; + if (m > 0) return `${m}${tr(lang, "分", "m")}${s}${tr(lang, "秒", "s")}`; + return `${s}${tr(lang, "秒", "s")}`; +} + +function fmtTs(ts: number | null | undefined, lang: Lang): string { + if (!ts) return "—"; + try { + return new Date(ts * 1000).toLocaleString(lang === "zh" ? "zh-CN" : "en-US", { + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + hour12: false, + }); + } catch { + return String(ts); + } +} + +function douyinUrl(session: RelaySession): string { + if (session.source_url?.includes("live.douyin.com")) return session.source_url; + if (session.source_room_id) return `https://live.douyin.com/${session.source_room_id}`; + return session.source_url || ""; +} + +export function LiveYoutubeRelayLogView() { + const [lang] = useState(() => { + if (typeof window === "undefined") return "zh"; + return window.localStorage.getItem("live.lang") === "en" ? "en" : "zh"; + }); + const initialProcess = + typeof window !== "undefined" + ? new URLSearchParams(window.location.search).get("process") || "youtube" + : "youtube"; + + const [process, setProcess] = useState(initialProcess); + const [q, setQ] = useState(""); + const [dateFrom, setDateFrom] = useState(""); + const [dateTo, setDateTo] = useState(""); + const [status, setStatus] = useState(""); + const [sessions, setSessions] = useState([]); + const [total, setTotal] = useState(0); + const [loading, setLoading] = useState(false); + const [importing, setImporting] = useState(false); + const [error, setError] = useState(""); + const [selected, setSelected] = useState(null); + const [offset, setOffset] = useState(0); + const limit = 50; + + const t = useCallback((zh: string, en: string) => tr(lang, zh, en), [lang]); + + const queryString = useMemo(() => { + const params = new URLSearchParams(); + if (process.trim()) params.set("process", process.trim()); + if (q.trim()) params.set("q", q.trim()); + if (dateFrom) params.set("date_from", dateFrom); + if (dateTo) params.set("date_to", dateTo); + if (status) params.set("status", status); + params.set("limit", String(limit)); + params.set("offset", String(offset)); + return params.toString(); + }, [process, q, dateFrom, dateTo, status, offset]); + + const loadSessions = useCallback(async () => { + setLoading(true); + setError(""); + try { + const data = await fetchJsonResponse<{ sessions?: RelaySession[]; total?: number }>( + `/hub/youtube/relay/sessions?${queryString}`, + ); + setSessions(data.sessions || []); + setTotal(Number(data.total) || 0); + } catch (e) { + setError((e as Error).message); + } finally { + setLoading(false); + } + }, [queryString]); + + useEffect(() => { + void loadSessions(); + }, [loadSessions]); + + const importLogs = useCallback(async () => { + setImporting(true); + setError(""); + try { + await fetchJsonResponse("/hub/youtube/relay/sessions/import-log", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ process: process.trim() || "youtube", replace_imported: true }), + }); + setOffset(0); + await loadSessions(); + } catch (e) { + setError((e as Error).message); + } finally { + setImporting(false); + } + }, [loadSessions, process]); + + const pageCount = Math.max(1, Math.ceil(total / limit)); + const pageIndex = Math.floor(offset / limit) + 1; + + return ( +
+
+
+
+

{t("YouTube 推流日志", "YouTube relay log")}

+

+ {t( + "记录每次抖音源转播到 YouTube 的时段、主播昵称、直播间 URL 与开播截图,便于追溯音乐版权等问题。", + "Track each Douyin-to-YouTube relay with anchor, room URL, timing, and start snapshot for copyright tracing.", + )} +

+
+
+ + +
+
+ +
+ + + + + +
+ + {error ?
{error}
: null} + +
+
+ + + + + + + + + + + + + + + + {sessions.map((session) => { + const url = douyinUrl(session); + return ( + setSelected(session)} + > + + + + + + + + + + + ); + })} + {!loading && sessions.length === 0 ? ( + + + + ) : null} + +
{t("截图", "Cover")}{t("主播昵称", "Anchor")}{t("直播间 URL", "Room URL")}{t("推流开始", "Started")}{t("推流结束", "Ended")}{t("总时长", "Duration")}{t("推流日期", "Date")}{t("YT 密钥", "YT key")}{t("线路", "Lane")}
+ {session.cover_url ? ( + // eslint-disable-next-line @next/next/no-img-element + {session.anchor_name + ) : ( +
+ N/A +
+ )} +
{session.anchor_name || "—"} + {url ? ( + e.stopPropagation()} + > + {url.replace(/^https?:\/\//, "")} + + ) : ( + "—" + )} + {fmtTs(session.started_at, lang)} + {session.ended_at ? fmtTs(session.ended_at, lang) : t("进行中", "Active")} + + {fmtDuration(session.duration_seconds, lang)} + {session.push_date || "—"} + {session.youtube_key_suffix ? `…${session.youtube_key_suffix}` : "—"} + + {session.channel_name || session.process || "—"} +
+ {t("暂无推流记录。可先点击「从 PM2 日志导入历史」。", "No relay sessions yet. Try importing PM2 logs first.")} +
+
+
+ +
+ + {t("共", "Total")} {total} {t("条", "records")} · {t("第", "Page")} {pageIndex}/{pageCount} + +
+ + +
+
+
+ + {selected ? ( +
setSelected(null)} + > +
e.stopPropagation()} + > +
+
+

{selected.anchor_name || t("推流详情", "Relay detail")}

+

{selected.stream_title || "—"}

+
+ +
+
+ {selected.cover_url ? ( + // eslint-disable-next-line @next/next/no-img-element + {selected.anchor_name + ) : null} +
+
+
{t("直播间 URL", "Room URL")}
+
+ {douyinUrl(selected) ? ( + + {douyinUrl(selected)} + + ) : ( + "—" + )} +
+
+
+
{t("房间号", "Room id")}
+
{selected.source_room_id || "—"}
+
+
+
{t("推流开始", "Started")}
+
{fmtTs(selected.started_at, lang)}
+
+
+
{t("推流结束", "Ended")}
+
{selected.ended_at ? fmtTs(selected.ended_at, lang) : t("进行中", "Active")}
+
+
+
{t("总时长", "Duration")}
+
{fmtDuration(selected.duration_seconds, lang)}
+
+
+
{t("推流日期", "Push date")}
+
{selected.push_date || "—"}
+
+
+
{t("线路 / 进程", "Lane / process")}
+
+ {selected.channel_name ? `${selected.channel_name} · ` : ""} + {selected.process || "—"} +
+
+
+
{t("结束原因", "End reason")}
+
{selected.end_reason || "—"}
+
+
+
{t("YouTube 推流密钥(后6位)", "YouTube stream key (last 6)")}
+
{selected.youtube_key_suffix ? `…${selected.youtube_key_suffix}` : "—"}
+
+
+
+
+
+ ) : null} +
+ ); +} + +export default LiveYoutubeRelayLogView; diff --git a/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx b/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx index de0a9cd..8b22573 100644 --- a/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx +++ b/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx @@ -1,6 +1,6 @@ "use client"; -import { Activity, AlertTriangle, Ban, Clock, Database, ExternalLink, Eye, History, Loader2, MonitorPlay, Play, Plus, Radio, RefreshCw, Square, Trash2 } from "lucide-react"; +import { Activity, AlertTriangle, Ban, Clock, Database, ExternalLink, Eye, History, Loader2, MonitorPlay, Play, Plus, Radio, RefreshCw, ScrollText, Square, Trash2 } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { @@ -187,6 +187,9 @@ const HIDE_YOUTUBE_QUALITY_GUARD = true; /** UI 隐藏「直播事件中枢」板块 */ const HIDE_YOUTUBE_LIVE_EVENT_HUB = true; +/** UI 隐藏「当前直播日志」整张卡片(改 false 可恢复) */ +const HIDE_YOUTUBE_LIVE_PROCESS_LOG = false; + type ProLaneDraft = { name: string; streamKey: string; @@ -213,15 +216,23 @@ function laneDraftsFromChannels(channels: YoutubeProChannel[]): Record { + if (HIDE_YOUTUBE_LIVE_EVENT_HUB) return; void refreshLiveEvents(null); if (liveEventsPollIntervalMs <= 0) return; const id = window.setInterval(() => void refreshLiveEvents(), liveEventsPollIntervalMs); @@ -1992,6 +2012,7 @@ export function LiveYoutubeUnmannedView({ ); useEffect(() => { + if (HIDE_YOUTUBE_QUALITY_GUARD) return; void refreshQualityGuard(); if (qualityGuardPollIntervalMs <= 0) return; const id = window.setInterval(() => void refreshQualityGuard(), qualityGuardPollIntervalMs); @@ -2031,6 +2052,7 @@ export function LiveYoutubeUnmannedView({ [statusLogActivity, pageVisible], ); const singleOnline = pm2StatusOnline(statusForPm2(singleRuntimeProc)); + const singlePushing = procStartBlocked(singleRow); const activeSourceDisplay = active ? douyinSourceDisplayFor(rowForPm2(resolveChannelPm2(active)), proUrlDraft || active.urlLines || "") : ""; @@ -3136,12 +3158,13 @@ export function LiveYoutubeUnmannedView({ ))} -
+
+
@@ -3217,6 +3251,7 @@ export function LiveYoutubeUnmannedView({ const dUrl = douyinSourceUrlFor(row, laneUrlText); const suf = parseYoutubeStreamKeySuffix(`key = ${laneKeyText}`); const rowOnline = pm2StatusOnline(st); + const rowPushing = procStartBlocked(row); const laneIndex = channels.findIndex((row) => row.id === c.id); const laneNeko = resolveNekoBrowserLink(nekoLinks, laneIndex).link; const laneName = cleanLaneName(c.name, laneIndex >= 0 ? laneIndex : 0); @@ -3329,6 +3364,7 @@ export function LiveYoutubeUnmannedView({ targetPm2={pm} busy={busy} online={rowOnline} + pushing={rowPushing} label={t("开始", "Start")} className="rounded-lg bg-emerald-500/20 text-emerald-100 ring-emerald-500/30" baseLock={false} @@ -3342,6 +3378,7 @@ export function LiveYoutubeUnmannedView({ targetPm2={pm} busy={busy} online={rowOnline} + pushing={rowPushing} label={t("停止", "Stop")} className="rounded-lg bg-rose-500/15 text-rose-100 ring-rose-500/25" baseLock={false} @@ -3355,6 +3392,7 @@ export function LiveYoutubeUnmannedView({ targetPm2={pm} busy={busy} online={rowOnline} + pushing={rowPushing} label={t("重新开始", "Restart")} className="rounded-lg bg-amber-500/15 text-amber-100 ring-amber-500/25" baseLock={false} @@ -3363,6 +3401,15 @@ export function LiveYoutubeUnmannedView({ t={t} compact /> + {laneNeko ? (
正在连接控制台...
\ No newline at end of file +无人直播系统 · live.local
← 返回门户首页无人直播 · 本页需与 API 同域(推荐 live.local:8001)

控制平面 · ARM Linux 开发板

无人直播控制中心

ShellCrash 负责代理上网;本机 FFmpeg 处理推流或 HDMI;Neko(Docker Chromium)或本机 Chromium 负责浏览器侧;开发板通过 USB 双头线 ADB 控制 AOSP。各模块独立,可分别启停。

live.local · unknown · unknown
正在连接控制台...
\ No newline at end of file diff --git a/d2ypp2/web-console/out/android.txt b/d2ypp2/web-console/out/android.txt index 60c9c33..e12c47b 100644 --- a/d2ypp2/web-console/out/android.txt +++ b/d2ypp2/web-console/out/android.txt @@ -2,6 +2,6 @@ 3:I[7588,["335","static/chunks/335-15aa194ced88957b.js","653","static/chunks/653-15975e374f8e28da.js","357","static/chunks/app/android/page-6fdeef4fee9d1d0a.js"],"default",1] 4:I[176,[],""] 5:I[9414,[],""] -0:["Jqppvm3nEc-9rVyR_dlnQ",[[["",{"children":["android",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["android",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","android","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/fe52682c84a4aff8.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]] +0:["xYg2qS760UEpBRHWcTFN5",[[["",{"children":["android",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["android",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","android","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/27b4d6b789fddb24.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/_next/static/css/f72551e7a5dadbbb.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] 1:null diff --git a/d2ypp2/web-console/out/console.html b/d2ypp2/web-console/out/console.html index f0df316..5bdf9de 100644 --- a/d2ypp2/web-console/out/console.html +++ b/d2ypp2/web-console/out/console.html @@ -1 +1 @@ -无人直播系统 · live.local
← 返回门户首页无人直播 · 本页需与 API 同域(推荐 live.local:8001)

控制平面 · ARM Linux 开发板

无人直播控制中心

ShellCrash 负责代理上网;本机 FFmpeg 处理推流或 HDMI;Neko(Docker Chromium)或本机 Chromium 负责浏览器侧;开发板通过 USB 双头线 ADB 控制 AOSP。各模块独立,可分别启停。

live.local · unknown · unknown
正在连接控制台...
\ No newline at end of file +无人直播系统 · live.local
← 返回门户首页无人直播 · 本页需与 API 同域(推荐 live.local:8001)

控制平面 · ARM Linux 开发板

无人直播控制中心

ShellCrash 负责代理上网;本机 FFmpeg 处理推流或 HDMI;Neko(Docker Chromium)或本机 Chromium 负责浏览器侧;开发板通过 USB 双头线 ADB 控制 AOSP。各模块独立,可分别启停。

live.local · unknown · unknown
正在连接控制台...
\ No newline at end of file diff --git a/d2ypp2/web-console/out/console.txt b/d2ypp2/web-console/out/console.txt index b31f4c5..61d3ca6 100644 --- a/d2ypp2/web-console/out/console.txt +++ b/d2ypp2/web-console/out/console.txt @@ -2,6 +2,6 @@ 3:I[8422,["335","static/chunks/335-15aa194ced88957b.js","653","static/chunks/653-15975e374f8e28da.js","443","static/chunks/app/console/page-a3e7b4f0539e497a.js"],"default",1] 4:I[176,[],""] 5:I[9414,[],""] -0:["Jqppvm3nEc-9rVyR_dlnQ",[[["",{"children":["console",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["console",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","console","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/fe52682c84a4aff8.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]] +0:["xYg2qS760UEpBRHWcTFN5",[[["",{"children":["console",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["console",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","console","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/27b4d6b789fddb24.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/_next/static/css/f72551e7a5dadbbb.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] 1:null diff --git a/d2ypp2/web-console/out/index.html b/d2ypp2/web-console/out/index.html index 256f19c..6ef24e1 100644 --- a/d2ypp2/web-console/out/index.html +++ b/d2ypp2/web-console/out/index.html @@ -1 +1 @@ -无人直播系统 · live.local

总览

live.local · 夜间 · 前台自动刷新 · 最后同步 未同步

\ No newline at end of file +无人直播系统 · live.local

总览

live.local · 夜间 · 前台自动刷新 · 最后同步 未同步

\ No newline at end of file diff --git a/d2ypp2/web-console/out/index.txt b/d2ypp2/web-console/out/index.txt index 96805db..25436b5 100644 --- a/d2ypp2/web-console/out/index.txt +++ b/d2ypp2/web-console/out/index.txt @@ -1,7 +1,7 @@ 2:I[7523,[],"ClientPageRoot"] -3:I[3372,["335","static/chunks/335-15aa194ced88957b.js","993","static/chunks/993-129e962f465be66e.js","653","static/chunks/653-15975e374f8e28da.js","371","static/chunks/371-68d9fd2d1d6e3507.js","931","static/chunks/app/page-ac6a25d785cd2760.js"],"default",1] +3:I[3372,["335","static/chunks/335-15aa194ced88957b.js","270","static/chunks/270-ee064b8a2cee7977.js","653","static/chunks/653-15975e374f8e28da.js","371","static/chunks/371-bddad8b92b1ea180.js","931","static/chunks/app/page-da87e47f3337d8f4.js"],"default",1] 4:I[176,[],""] 5:I[9414,[],""] -0:["Jqppvm3nEc-9rVyR_dlnQ",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/fe52682c84a4aff8.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]] +0:["xYg2qS760UEpBRHWcTFN5",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/27b4d6b789fddb24.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/_next/static/css/f72551e7a5dadbbb.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] 1:null diff --git a/d2ypp2/web-console/out/shellcrash.html b/d2ypp2/web-console/out/shellcrash.html index 3cbacf1..6065e9b 100644 --- a/d2ypp2/web-console/out/shellcrash.html +++ b/d2ypp2/web-console/out/shellcrash.html @@ -1 +1 @@ -无人直播系统 · live.local
← 返回门户首页无人直播 · 本页需与 API 同域(推荐 live.local:8001)

控制平面 · ARM Linux 开发板

无人直播控制中心

ShellCrash 负责代理上网;本机 FFmpeg 处理推流或 HDMI;Neko(Docker Chromium)或本机 Chromium 负责浏览器侧;开发板通过 USB 双头线 ADB 控制 AOSP。各模块独立,可分别启停。

live.local · unknown · unknown
正在连接控制台...
\ No newline at end of file +无人直播系统 · live.local
← 返回门户首页无人直播 · 本页需与 API 同域(推荐 live.local:8001)

控制平面 · ARM Linux 开发板

无人直播控制中心

ShellCrash 负责代理上网;本机 FFmpeg 处理推流或 HDMI;Neko(Docker Chromium)或本机 Chromium 负责浏览器侧;开发板通过 USB 双头线 ADB 控制 AOSP。各模块独立,可分别启停。

live.local · unknown · unknown
正在连接控制台...
\ No newline at end of file diff --git a/d2ypp2/web-console/out/shellcrash.txt b/d2ypp2/web-console/out/shellcrash.txt index 8ea8b1d..67273f6 100644 --- a/d2ypp2/web-console/out/shellcrash.txt +++ b/d2ypp2/web-console/out/shellcrash.txt @@ -2,6 +2,6 @@ 3:I[4825,["335","static/chunks/335-15aa194ced88957b.js","653","static/chunks/653-15975e374f8e28da.js","6","static/chunks/app/shellcrash/page-af8576bff9fa13fc.js"],"default",1] 4:I[176,[],""] 5:I[9414,[],""] -0:["Jqppvm3nEc-9rVyR_dlnQ",[[["",{"children":["shellcrash",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["shellcrash",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","shellcrash","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/fe52682c84a4aff8.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]] +0:["xYg2qS760UEpBRHWcTFN5",[[["",{"children":["shellcrash",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["shellcrash",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","shellcrash","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/27b4d6b789fddb24.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/_next/static/css/f72551e7a5dadbbb.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] 1:null diff --git a/d2ypp2/web-console/out/youtube-events.html b/d2ypp2/web-console/out/youtube-events.html index fd04698..063eaa5 100644 --- a/d2ypp2/web-console/out/youtube-events.html +++ b/d2ypp2/web-console/out/youtube-events.html @@ -1 +1 @@ -无人直播系统 · live.local

总览

live.local · 夜间 · 前台自动刷新 · 最后同步 未同步

\ No newline at end of file +无人直播系统 · live.local

总览

live.local · 夜间 · 前台自动刷新 · 最后同步 未同步

\ No newline at end of file diff --git a/d2ypp2/web-console/out/youtube-events.txt b/d2ypp2/web-console/out/youtube-events.txt index 439b764..aa850bc 100644 --- a/d2ypp2/web-console/out/youtube-events.txt +++ b/d2ypp2/web-console/out/youtube-events.txt @@ -1,7 +1,7 @@ 2:I[7523,[],"ClientPageRoot"] -3:I[8307,["335","static/chunks/335-15aa194ced88957b.js","993","static/chunks/993-129e962f465be66e.js","653","static/chunks/653-15975e374f8e28da.js","371","static/chunks/371-68d9fd2d1d6e3507.js","851","static/chunks/app/youtube-events/page-3cdf4daf192541a7.js"],"default",1] +3:I[8307,["335","static/chunks/335-15aa194ced88957b.js","270","static/chunks/270-ee064b8a2cee7977.js","653","static/chunks/653-15975e374f8e28da.js","371","static/chunks/371-bddad8b92b1ea180.js","851","static/chunks/app/youtube-events/page-6cfcc966a308c73f.js"],"default",1] 4:I[176,[],""] 5:I[9414,[],""] -0:["Jqppvm3nEc-9rVyR_dlnQ",[[["",{"children":["youtube-events",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["youtube-events",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","youtube-events","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/fe52682c84a4aff8.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]] +0:["xYg2qS760UEpBRHWcTFN5",[[["",{"children":["youtube-events",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["youtube-events",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","youtube-events","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/27b4d6b789fddb24.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/_next/static/css/f72551e7a5dadbbb.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] 1:null diff --git a/d2ypp2/web-console/out/youtube-relay-log.html b/d2ypp2/web-console/out/youtube-relay-log.html new file mode 100644 index 0000000..bc9ac7e --- /dev/null +++ b/d2ypp2/web-console/out/youtube-relay-log.html @@ -0,0 +1 @@ +无人直播系统 · live.local

YouTube 推流日志

记录每次抖音源转播到 YouTube 的时段、主播昵称、直播间 URL 与开播截图,便于追溯音乐版权等问题。

截图主播昵称直播间 URL推流开始推流结束总时长推流日期YT 密钥线路
暂无推流记录。可先点击「从 PM2 日志导入历史」。
共 0 条 · 第 1/1
\ No newline at end of file diff --git a/d2ypp2/web-console/out/youtube-relay-log.txt b/d2ypp2/web-console/out/youtube-relay-log.txt new file mode 100644 index 0000000..d4e582f --- /dev/null +++ b/d2ypp2/web-console/out/youtube-relay-log.txt @@ -0,0 +1,7 @@ +2:I[7523,[],"ClientPageRoot"] +3:I[3211,["614","static/chunks/app/youtube-relay-log/page-44c22a5313590d69.js"],"default",1] +4:I[176,[],""] +5:I[9414,[],""] +0:["xYg2qS760UEpBRHWcTFN5",[[["",{"children":["youtube-relay-log",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["youtube-relay-log",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","youtube-relay-log","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/27b4d6b789fddb24.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/_next/static/css/f72551e7a5dadbbb.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]] +6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] +1:null diff --git a/d2ypp2/web.py b/d2ypp2/web.py index 2fa331d..713c104 100644 --- a/d2ypp2/web.py +++ b/d2ypp2/web.py @@ -107,6 +107,13 @@ from src.youtube_live_store import ( record_process_observation, youtube_live_summary, ) +from src.youtube_relay_log import ( + get_relay_cover_path, + get_relay_session, + import_relay_sessions_for_process, + list_relay_sessions, + sync_relay_from_recent_log, +) from src.youtube_quality_guard import build_youtube_quality_guard_report # ---------------- 配置(根目录结构) ---------------- @@ -508,6 +515,10 @@ async def _record_youtube_control_event(process: str, action: str, script: str, mode=ctx["mode"], note=note, ) + if action in {"stop", "finish", "end", "restart"}: + from src.youtube_relay_log import close_active_relay_sessions + + await asyncio.to_thread(close_active_relay_sessions, process, reason=action) async def _record_youtube_status_observation(process: str, payload: dict[str, Any]) -> None: @@ -518,6 +529,13 @@ async def _record_youtube_status_observation(process: str, payload: dict[str, An _YOUTUBE_EVENT_STATUS_CACHE[process] = now ctx = _youtube_event_context(process) await asyncio.to_thread(record_process_observation, process, payload, url_lines=ctx["url_lines"]) + await asyncio.to_thread( + sync_relay_from_recent_log, + process, + str(payload.get("recent_log") or ""), + channel_name=str(ctx.get("channel_name") or ""), + url_lines=str(ctx.get("url_lines") or ""), + ) async def _process_runtime_identity(process: str) -> tuple[int, int | None]: @@ -2266,6 +2284,65 @@ async def youtube_events_page(): return await index() +@app.get("/youtube-relay-log", include_in_schema=False) +async def youtube_relay_log_page(): + route_file = _console_route_html("youtube-relay-log") + if route_file: + return _console_html_response(route_file) + return await index() + + +@app.get("/hub/youtube/relay/sessions", include_in_schema=False) +async def hub_youtube_relay_sessions( + process: str = "", + q: str = "", + date_from: str = "", + date_to: str = "", + status: str = "", + limit: int = 50, + offset: int = 0, +): + return await asyncio.to_thread( + list_relay_sessions, + process=process, + q=q, + date_from=date_from, + date_to=date_to, + status=status, + limit=limit, + offset=offset, + ) + + +@app.get("/hub/youtube/relay/sessions/{session_id}", include_in_schema=False) +async def hub_youtube_relay_session_detail(session_id: str): + session = await asyncio.to_thread(get_relay_session, session_id) + if not session: + return JSONResponse({"error": "relay session not found"}, status_code=404) + return {"session": session} + + +@app.get("/hub/youtube/relay/sessions/{session_id}/cover", include_in_schema=False) +async def hub_youtube_relay_session_cover(session_id: str): + path = await asyncio.to_thread(get_relay_cover_path, session_id) + if not path: + return JSONResponse({"error": "cover not found"}, status_code=404) + return FileResponse(str(path), media_type="image/jpeg") + + +@app.post("/hub/youtube/relay/sessions/import-log", include_in_schema=False) +async def hub_youtube_relay_sessions_import_log(body: dict[str, Any]): + process = str(body.get("process") or "youtube") + out_path = str(body.get("log_path") or "").strip() or None + replace_imported = bool(body.get("replace_imported")) + return await asyncio.to_thread( + import_relay_sessions_for_process, + process, + out_path=out_path, + replace_imported=replace_imported, + ) + + @app.get("/console", include_in_schema=False) async def console_page(): route_file = _console_route_html("console") diff --git a/d2ypp2/youtube.py b/d2ypp2/youtube.py index 35a2941..05a9bf7 100644 --- a/d2ypp2/youtube.py +++ b/d2ypp2/youtube.py @@ -41,6 +41,13 @@ from src import spider, stream from src.proxy import ProxyDetector from src.runtime_bootstrap import load_msg_push_exports from src.youtube_config_paths import resolve_youtube_style_config_paths +from src.youtube_relay_slot import ( + claim_relay_slot, + prune_orphan_relay_recording, + relay_slot_blocks, + release_relay_slot, + youtube_stream_fallback_urls, +) from src.youtube_runtime import normalize_youtube_video_save_type from src.recorder_config import read_recorder_setting, recorder_config_target_path, SHARED_RECORDER_SECTIONS from src.utils import logger @@ -70,6 +77,8 @@ error_window_size = 10 error_threshold = 5 monitoring = 0 running_list = [] +active_monitor_urls: set[str] = set() +_semaphore_holder: dict[str, Any] = {"semaphore": None, "limit": 0} url_tuples_list = [] url_comments = [] text_no_repeat_url = [] @@ -107,6 +116,14 @@ os.environ['PATH'] = ffmpeg_path + os.pathsep + current_env_path def signal_handler(_signal, _frame): + global exit_recording + exit_recording = True + try: + from src.youtube_relay_heartbeat import clear_relay_heartbeat + + clear_relay_heartbeat(_live_pm2_name() or "youtube", base_dir=script_path) + except Exception: + pass sys.exit(0) @@ -484,6 +501,12 @@ def run_script(command: str) -> None: def clear_record_info(record_name: str, record_url: str) -> None: global monitoring recording.discard(record_name) + recording_time_list.pop(record_name, None) + release_relay_slot( + record_name, + pm2=_live_pm2_name() or "youtube", + base_dir=script_path, + ) if record_url in url_comments and record_url in running_list: running_list.remove(record_url) monitoring -= 1 @@ -591,6 +614,11 @@ def check_subprocess(record_name: str, record_url: str, ffmpeg_command: list, sa color_obj.print_colored(f"\n{record_name} {stop_time} 直播录制出错,返回码: {return_code}\n", color_obj.RED) recording.discard(record_name) + release_relay_slot( + record_name, + pm2=_live_pm2_name() or "youtube", + base_dir=script_path, + ) return False @@ -678,6 +706,12 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None: # print(f'\r代理地址:{proxy_address}') # print(f'\r全局代理:{global_proxy}') while True: + if record_url not in active_monitor_urls: + if record_url in running_list: + running_list.remove(record_url) + global monitoring + monitoring = len(running_list) + return try: port_info = [] if record_url.find("douyin.com/") > -1: @@ -1178,12 +1212,6 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None: push_at = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S') if port_info['is_live'] is False: print(f"\r{record_name} 等待直播... ") - - # 直接退出线程eric - # return - # 继续循环 - continue - if start_pushed: if over_show_push: push_content = "直播间状态更新:[直播间名称] 直播已结束!时间:[时间]" @@ -1198,15 +1226,19 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None: daemon=True ).start() start_pushed = False + continue else: content = f"\r{record_name} 正在直播中..." print(content) - # 检查是否已有直播在录制 - if len(recording) > 0 : - # 如果已有直播在录制,跳过这次录制(主播在线) - # return - continue #如果在循环中 + prune_orphan_relay_recording( + recording, + recording_time_list, + pm2=_live_pm2_name() or "youtube", + base_dir=script_path, + ) + if relay_slot_blocks(record_name, recording): + continue if live_status_push and not start_pushed: if begin_show_push: @@ -1315,7 +1347,15 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None: if proxy_address: ffmpeg_command.insert(1, "-http_proxy") ffmpeg_command.insert(2, proxy_address) - + + if not claim_relay_slot( + record_name, + pm2=_live_pm2_name() or "youtube", + base_dir=script_path, + anchor_name=anchor_name, + ): + continue + recording.add(record_name) start_record_time = datetime.datetime.now() recording_time_list[record_name] = [start_record_time, record_quality_zh] @@ -1638,25 +1678,29 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None: else: from douyin_youtube_ffplay import start_douyin_youtube_ffplay - _fallback_urls = [ - u for u in url_line_list - if isinstance(u, str) and u.strip() and u.strip() != real_url.strip() - ] - start_douyin_youtube_ffplay( - title=title_in_name, - anchor_name=anchor_name, - real_url=real_url, - rec_info=rec_info, - record_name=record_name, - recording=recording, - recording_time_list=recording_time_list, - running_list=running_list, - clear_record_info=clear_record_info, - color_obj=color_obj, - config_file=config_file, - record_url=record_url, - fallback_urls=_fallback_urls, - ) + _fallback_urls = youtube_stream_fallback_urls(port_info, real_url) + try: + start_douyin_youtube_ffplay( + title=title_in_name, + anchor_name=anchor_name, + real_url=real_url, + rec_info=rec_info, + record_name=record_name, + recording=recording, + recording_time_list=recording_time_list, + running_list=running_list, + clear_record_info=clear_record_info, + color_obj=color_obj, + config_file=config_file, + record_url=record_url, + fallback_urls=_fallback_urls, + ) + except Exception as relay_exc: + logger.error( + f"YouTube 推流异常: {relay_exc} " + f"发生错误的行数: {relay_exc.__traceback__.tb_lineno}" + ) + clear_record_info(record_name, record_url) count_time = time.time() @@ -1868,6 +1912,8 @@ except Exception as err: while True: + config_file, url_config_file = _youtube_pro_style_config_paths() + try: if not os.path.isfile(config_file): with open(config_file, 'w', encoding=text_encoding) as file: @@ -1879,6 +1925,10 @@ while True: ini_URL_content = file.read().strip() if not ini_URL_content.strip(): + if _live_pm2_name() or not sys.stdin.isatty(): + logger.warning("URL_config 为空,等待控制台配置…") + time.sleep(10) + continue input_url = input('请输入要录制的主播直播间网址(尽量使用PC网页端的直播间地址):\n') with open(url_config_file, 'w', encoding=text_encoding) as file: file.write(input_url) @@ -1897,7 +1947,10 @@ while True: proxy_addr_bak = read_config_value(config, '录制设置', '代理地址', "") proxy_addr = None if not use_proxy else proxy_addr_bak max_request = int(read_config_value(config, '录制设置', '同一时间访问网络的线程数', 3)) - semaphore = threading.Semaphore(max_request) + if _semaphore_holder["limit"] != max_request or _semaphore_holder["semaphore"] is None: + _semaphore_holder["semaphore"] = threading.Semaphore(max_request) + _semaphore_holder["limit"] = max_request + semaphore = _semaphore_holder["semaphore"] delay_default = int(read_config_value(config, '录制设置', '循环时间(秒)', 120)) local_delay_default = int(read_config_value(config, '录制设置', '排队读取网址时间(秒)', 0)) loop_time = options.get(read_config_value(config, '录制设置', '是否显示循环秒数', "否"), False) @@ -2206,6 +2259,8 @@ while True: update_file(url_config_file, old_str=replace_words[0], new_str=new_word, start_str=start_with) text_no_repeat_url = list(set(url_tuples_list)) + active_monitor_urls.clear() + active_monitor_urls.update(item[1] for item in text_no_repeat_url) if len(text_no_repeat_url) > 0: for url_tuple in text_no_repeat_url: