Add YouTube relay log tooling and optional hub service controls.
This captures the current live stack updates across the API, Linux service scripts, tests, diagnostics, and exported console assets so the Ubuntu deployment can pull a consistent test3 build. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
fe577c6536
commit
278b48497e
@ -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
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "android_panel",
|
||||
"layer": "infra",
|
||||
"enabled": true,
|
||||
"enabled": false,
|
||||
"manager": "systemd",
|
||||
"ports": { "http": 5000 },
|
||||
"env": {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "filebrowser",
|
||||
"layer": "infra",
|
||||
"enabled": true,
|
||||
"enabled": false,
|
||||
"manager": "docker",
|
||||
"ports": { "http": 8082 },
|
||||
"env": {
|
||||
|
||||
@ -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"
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "homeassistant",
|
||||
"layer": "studio",
|
||||
"enabled": true,
|
||||
"enabled": false,
|
||||
"manager": "docker",
|
||||
"ports": { "http": 8123 },
|
||||
"env": {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "homepage",
|
||||
"layer": "infra",
|
||||
"enabled": true,
|
||||
"enabled": false,
|
||||
"manager": "docker",
|
||||
"ports": { "http": 3080 },
|
||||
"env": { "ENABLE_HOMEPAGE": "1", "HOMEPAGE_PORT": "3080" }
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "ntfy",
|
||||
"layer": "studio",
|
||||
"enabled": true,
|
||||
"enabled": false,
|
||||
"manager": "docker",
|
||||
"ports": { "http": 8089 },
|
||||
"env": {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "srs",
|
||||
"layer": "infra",
|
||||
"enabled": true,
|
||||
"enabled": false,
|
||||
"manager": "docker",
|
||||
"ports": {
|
||||
"http": 8080,
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "webtty",
|
||||
"layer": "core",
|
||||
"enabled": true,
|
||||
"enabled": false,
|
||||
"manager": "systemd",
|
||||
"ports": { "http": 7681 },
|
||||
"env": {
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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" <<YAML
|
||||
- WebTTY:
|
||||
href: http://${HOSTNAME_ALIAS}.local:${WEBTTY_PORT}
|
||||
@ -2639,14 +2687,14 @@ YAML
|
||||
description: System administration
|
||||
YAML
|
||||
fi
|
||||
if [ "${ENABLE_FILEBROWSER:-1}" = "1" ]; then
|
||||
if [ "${ENABLE_FILEBROWSER:-0}" = "1" ]; then
|
||||
cat >>"$target" <<YAML
|
||||
- File Browser:
|
||||
href: http://${HOSTNAME_ALIAS}.local:${FILEBROWSER_PORT}
|
||||
description: Beginner-friendly file manager
|
||||
YAML
|
||||
fi
|
||||
if [ "${ENABLE_ANDROID_PANEL:-1}" = "1" ]; then
|
||||
if [ "${ENABLE_ANDROID_PANEL:-0}" = "1" ]; then
|
||||
cat >>"$target" <<YAML
|
||||
- Android Center:
|
||||
href: http://${HOSTNAME_ALIAS}.local:${PORT}/android
|
||||
@ -2667,56 +2715,56 @@ YAML
|
||||
description: Metrics and health monitoring
|
||||
YAML
|
||||
fi
|
||||
if [ "${ENABLE_MITMPROXY:-1}" = "1" ]; then
|
||||
if [ "${ENABLE_MITMPROXY:-0}" = "1" ]; then
|
||||
cat >>"$target" <<YAML
|
||||
- mitmproxy:
|
||||
href: http://${HOSTNAME_ALIAS}.local:${MITMPROXY_WEB_PORT}
|
||||
description: Web proxy capture and traffic inspection
|
||||
YAML
|
||||
fi
|
||||
if [ "${ENABLE_VSCODE_SERVER:-1}" = "1" ]; then
|
||||
if [ "${ENABLE_VSCODE_SERVER:-0}" = "1" ]; then
|
||||
cat >>"$target" <<YAML
|
||||
- VS Code Server:
|
||||
href: http://${HOSTNAME_ALIAS}.local:${VSCODE_SERVER_PORT}
|
||||
description: Browser IDE mounted to the live workspace
|
||||
YAML
|
||||
fi
|
||||
if [ "${ENABLE_UPTIME_KUMA:-1}" = "1" ]; then
|
||||
if [ "${ENABLE_UPTIME_KUMA:-0}" = "1" ]; then
|
||||
cat >>"$target" <<YAML
|
||||
- Uptime Kuma:
|
||||
href: http://${HOSTNAME_ALIAS}.local:${UPTIME_KUMA_PORT}
|
||||
description: Endpoint health checks and alert dashboards
|
||||
YAML
|
||||
fi
|
||||
if [ "${ENABLE_SRS:-1}" = "1" ]; then
|
||||
if [ "${ENABLE_SRS:-0}" = "1" ]; then
|
||||
cat >>"$target" <<YAML
|
||||
- SRS:
|
||||
href: http://${HOSTNAME_ALIAS}.local:${SRS_HTTP_PORT}
|
||||
description: RTMP, SRT and preview endpoint
|
||||
YAML
|
||||
fi
|
||||
if [ "${ENABLE_OPENCLAW:-1}" = "1" ]; then
|
||||
if [ "${ENABLE_OPENCLAW:-0}" = "1" ]; then
|
||||
cat >>"$target" <<YAML
|
||||
- OpenClaw:
|
||||
href: http://${HOSTNAME_ALIAS}.local:${OPENCLAW_GATEWAY_PORT}
|
||||
description: Multi-agent automation gateway and web workspace
|
||||
YAML
|
||||
fi
|
||||
if [ "${ENABLE_HOMEASSISTANT:-1}" = "1" ]; then
|
||||
if [ "${ENABLE_HOMEASSISTANT:-0}" = "1" ]; then
|
||||
cat >>"$target" <<YAML
|
||||
- Home Assistant:
|
||||
href: http://${HOSTNAME_ALIAS}.local:${HOMEASSISTANT_PORT}
|
||||
description: Local automation workspace
|
||||
YAML
|
||||
fi
|
||||
if [ "${ENABLE_FRIGATE:-1}" = "1" ]; then
|
||||
if [ "${ENABLE_FRIGATE:-0}" = "1" ]; then
|
||||
cat >>"$target" <<YAML
|
||||
- Frigate NVR:
|
||||
href: http://${HOSTNAME_ALIAS}.local:${FRIGATE_WEB_PORT}
|
||||
description: Camera NVR and detection console
|
||||
YAML
|
||||
fi
|
||||
if [ "${ENABLE_NTFY:-1}" = "1" ]; then
|
||||
if [ "${ENABLE_NTFY:-0}" = "1" ]; then
|
||||
cat >>"$target" <<YAML
|
||||
- ntfy:
|
||||
href: http://${HOSTNAME_ALIAS}.local:${NTFY_PORT}
|
||||
@ -2733,7 +2781,7 @@ YAML
|
||||
}
|
||||
|
||||
prepare_homepage() {
|
||||
if [ "${ENABLE_HOMEPAGE:-1}" != "1" ] || ! need_docker; then
|
||||
if [ "${ENABLE_HOMEPAGE:-0}" != "1" ] || ! need_docker; then
|
||||
return 0
|
||||
fi
|
||||
log "Preparing Homepage"
|
||||
@ -2754,7 +2802,7 @@ prepare_homepage() {
|
||||
}
|
||||
|
||||
prepare_filebrowser() {
|
||||
if [ "${ENABLE_FILEBROWSER:-1}" != "1" ] || ! need_docker; then
|
||||
if [ "${ENABLE_FILEBROWSER:-0}" != "1" ] || ! need_docker; then
|
||||
return 0
|
||||
fi
|
||||
log "Preparing File Browser"
|
||||
@ -2873,7 +2921,7 @@ PY
|
||||
}
|
||||
|
||||
prepare_mitmproxy() {
|
||||
if [ "${ENABLE_MITMPROXY:-1}" != "1" ] || ! need_docker; then
|
||||
if [ "${ENABLE_MITMPROXY:-0}" != "1" ] || ! need_docker; then
|
||||
return 0
|
||||
fi
|
||||
log "Preparing mitmproxy"
|
||||
@ -2885,7 +2933,7 @@ prepare_mitmproxy() {
|
||||
}
|
||||
|
||||
prepare_vscode_server() {
|
||||
if [ "${ENABLE_VSCODE_SERVER:-1}" != "1" ] || ! need_docker; then
|
||||
if [ "${ENABLE_VSCODE_SERVER:-0}" != "1" ] || ! need_docker; then
|
||||
return 0
|
||||
fi
|
||||
log "Preparing code-server"
|
||||
@ -2896,7 +2944,7 @@ prepare_vscode_server() {
|
||||
}
|
||||
|
||||
prepare_uptime_kuma() {
|
||||
if [ "${ENABLE_UPTIME_KUMA:-1}" != "1" ] || ! need_docker; then
|
||||
if [ "${ENABLE_UPTIME_KUMA:-0}" != "1" ] || ! need_docker; then
|
||||
return 0
|
||||
fi
|
||||
log "Preparing Uptime Kuma"
|
||||
@ -2907,7 +2955,7 @@ prepare_uptime_kuma() {
|
||||
}
|
||||
|
||||
prepare_openclaw() {
|
||||
if [ "${ENABLE_OPENCLAW:-1}" != "1" ] || ! need_docker; then
|
||||
if [ "${ENABLE_OPENCLAW:-0}" != "1" ] || ! need_docker; then
|
||||
return 0
|
||||
fi
|
||||
log "Preparing OpenClaw"
|
||||
@ -2920,7 +2968,7 @@ prepare_openclaw() {
|
||||
}
|
||||
|
||||
prepare_homeassistant() {
|
||||
if [ "${ENABLE_HOMEASSISTANT:-1}" != "1" ] || ! need_docker; then
|
||||
if [ "${ENABLE_HOMEASSISTANT:-0}" != "1" ] || ! need_docker; then
|
||||
return 0
|
||||
fi
|
||||
log "Preparing Home Assistant"
|
||||
@ -2936,7 +2984,7 @@ prepare_homeassistant() {
|
||||
}
|
||||
|
||||
prepare_frigate() {
|
||||
if [ "${ENABLE_FRIGATE:-1}" != "1" ] || ! need_docker; then
|
||||
if [ "${ENABLE_FRIGATE:-0}" != "1" ] || ! need_docker; then
|
||||
return 0
|
||||
fi
|
||||
log "Preparing Frigate"
|
||||
@ -2949,7 +2997,7 @@ prepare_frigate() {
|
||||
allow_tcp_port_if_firewall_active "$FRIGATE_RTSP_PORT"
|
||||
allow_tcp_port_if_firewall_active "$FRIGATE_WEBRTC_PORT"
|
||||
allow_udp_port_if_firewall_active "$FRIGATE_WEBRTC_PORT"
|
||||
if [ "${FRIGATE_USB_AUTOSTART:-1}" = "1" ]; then
|
||||
if [ "${FRIGATE_USB_AUTOSTART:-0}" = "1" ]; then
|
||||
bash "$SERVICE_CTL" frigate auto || log "WARN: Frigate USB auto-start check failed"
|
||||
install_frigate_usb_watch_service
|
||||
else
|
||||
@ -2959,7 +3007,7 @@ prepare_frigate() {
|
||||
}
|
||||
|
||||
prepare_ntfy() {
|
||||
if [ "${ENABLE_NTFY:-1}" != "1" ] || ! need_docker; then
|
||||
if [ "${ENABLE_NTFY:-0}" != "1" ] || ! need_docker; then
|
||||
return 0
|
||||
fi
|
||||
log "Preparing ntfy"
|
||||
@ -2992,7 +3040,7 @@ prepare_coturn() {
|
||||
}
|
||||
|
||||
install_frigate_usb_watch_service() {
|
||||
if [ "${ENABLE_FRIGATE:-1}" != "1" ] || [ "${FRIGATE_USB_AUTOSTART:-1}" != "1" ]; then
|
||||
if [ "${ENABLE_FRIGATE:-0}" != "1" ] || [ "${FRIGATE_USB_AUTOSTART:-0}" != "1" ]; then
|
||||
systemctl disable --now live-frigate-usb-watch.service >/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"
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
65
d2ypp2/scripts/linux/stop_optional_hub_services.sh
Normal file
65
d2ypp2/scripts/linux/stop_optional_hub_services.sh
Normal file
@ -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
|
||||
@ -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()}
|
||||
|
||||
1047
d2ypp2/src/youtube_relay_log.py
Normal file
1047
d2ypp2/src/youtube_relay_log.py
Normal file
File diff suppressed because it is too large
Load Diff
116
d2ypp2/src/youtube_relay_slot.py
Normal file
116
d2ypp2/src/youtube_relay_slot.py
Normal file
@ -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
|
||||
@ -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")
|
||||
|
||||
185
d2ypp2/tests/test_youtube_relay_log.py
Normal file
185
d2ypp2/tests/test_youtube_relay_log.py
Normal file
@ -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()
|
||||
80
d2ypp2/tests/test_youtube_relay_slot.py
Normal file
80
d2ypp2/tests/test_youtube_relay_slot.py
Normal file
@ -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()
|
||||
62
d2ypp2/tools/analyze_host03_room_sessions.py
Normal file
62
d2ypp2/tools/analyze_host03_room_sessions.py
Normal file
@ -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"))
|
||||
107
d2ypp2/tools/analyze_host03_youtube_log.py
Normal file
107
d2ypp2/tools/analyze_host03_youtube_log.py
Normal file
@ -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"))
|
||||
28
d2ypp2/tools/check_host03_deploy.py
Normal file
28
d2ypp2/tools/check_host03_deploy.py
Normal file
@ -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()
|
||||
148
d2ypp2/tools/check_relay_slot_hosts.py
Normal file
148
d2ypp2/tools/check_relay_slot_hosts.py
Normal file
@ -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)
|
||||
34
d2ypp2/tools/debug_host03_web_import.py
Normal file
34
d2ypp2/tools/debug_host03_web_import.py
Normal file
@ -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]}")
|
||||
90
d2ypp2/tools/deploy_neko_nat1to1_fix_host04.py
Normal file
90
d2ypp2/tools/deploy_neko_nat1to1_fix_host04.py
Normal file
@ -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())
|
||||
83
d2ypp2/tools/deploy_neko_nat1to1_fix_host05.py
Normal file
83
d2ypp2/tools/deploy_neko_nat1to1_fix_host05.py
Normal file
@ -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())
|
||||
151
d2ypp2/tools/deploy_relay_fix_all_hosts.py
Normal file
151
d2ypp2/tools/deploy_relay_fix_all_hosts.py
Normal file
@ -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")
|
||||
96
d2ypp2/tools/deploy_relay_log_fix_host03.py
Normal file
96
d2ypp2/tools/deploy_relay_log_fix_host03.py
Normal file
@ -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())
|
||||
130
d2ypp2/tools/deploy_relay_log_host03.py
Normal file
130
d2ypp2/tools/deploy_relay_log_host03.py
Normal file
@ -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())
|
||||
77
d2ypp2/tools/deploy_relay_slot_fix_237.py
Normal file
77
d2ypp2/tools/deploy_relay_slot_fix_237.py
Normal file
@ -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()
|
||||
163
d2ypp2/tools/deploy_relay_slot_fix_3hosts_safe.py
Normal file
163
d2ypp2/tools/deploy_relay_slot_fix_3hosts_safe.py
Normal file
@ -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.")
|
||||
104
d2ypp2/tools/deploy_relay_slot_fix_host03_host05.py
Normal file
104
d2ypp2/tools/deploy_relay_slot_fix_host03_host05.py
Normal file
@ -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")
|
||||
26
d2ypp2/tools/grep_host03_youtube_log.py
Normal file
26
d2ypp2/tools/grep_host03_youtube_log.py
Normal file
@ -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()
|
||||
17
d2ypp2/tools/inspect_pm2_log_sudo_host03.py
Normal file
17
d2ypp2/tools/inspect_pm2_log_sudo_host03.py
Normal file
@ -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()
|
||||
34
d2ypp2/tools/inspect_relay_log_host03.py
Normal file
34
d2ypp2/tools/inspect_relay_log_host03.py
Normal file
@ -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")
|
||||
27
d2ypp2/tools/query_host03_api.py
Normal file
27
d2ypp2/tools/query_host03_api.py
Normal file
@ -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])
|
||||
35
d2ypp2/tools/query_host03_downloads.py
Normal file
35
d2ypp2/tools/query_host03_downloads.py
Normal file
@ -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()
|
||||
33
d2ypp2/tools/query_host03_journal.py
Normal file
33
d2ypp2/tools/query_host03_journal.py
Normal file
@ -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()
|
||||
95
d2ypp2/tools/query_host03_lane1.py
Normal file
95
d2ypp2/tools/query_host03_lane1.py
Normal file
@ -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())
|
||||
57
d2ypp2/tools/query_host03_lane1_deep.py
Normal file
57
d2ypp2/tools/query_host03_lane1_deep.py
Normal file
@ -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())
|
||||
109
d2ypp2/tools/query_host03_lane1_samples.py
Normal file
109
d2ypp2/tools/query_host03_lane1_samples.py
Normal file
@ -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())
|
||||
48
d2ypp2/tools/query_host03_log_source.py
Normal file
48
d2ypp2/tools/query_host03_log_source.py
Normal file
@ -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()
|
||||
67
d2ypp2/tools/query_host03_logs_morning.py
Normal file
67
d2ypp2/tools/query_host03_logs_morning.py
Normal file
@ -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())
|
||||
68
d2ypp2/tools/query_host03_morning_logs2.py
Normal file
68
d2ypp2/tools/query_host03_morning_logs2.py
Normal file
@ -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())
|
||||
62
d2ypp2/tools/query_host03_opt_live.py
Normal file
62
d2ypp2/tools/query_host03_opt_live.py
Normal file
@ -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())
|
||||
74
d2ypp2/tools/query_host03_recordings.py
Normal file
74
d2ypp2/tools/query_host03_recordings.py
Normal file
@ -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()
|
||||
44
d2ypp2/tools/query_host03_root_log_grep.py
Normal file
44
d2ypp2/tools/query_host03_root_log_grep.py
Normal file
@ -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()
|
||||
57
d2ypp2/tools/query_host03_root_pm2_logs.py
Normal file
57
d2ypp2/tools/query_host03_root_pm2_logs.py
Normal file
@ -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()
|
||||
66
d2ypp2/tools/query_host03_runtime.py
Normal file
66
d2ypp2/tools/query_host03_runtime.py
Normal file
@ -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()
|
||||
76
d2ypp2/tools/query_host03_samples_today.py
Normal file
76
d2ypp2/tools/query_host03_samples_today.py
Normal file
@ -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()
|
||||
55
d2ypp2/tools/query_host03_snapshot_search.py
Normal file
55
d2ypp2/tools/query_host03_snapshot_search.py
Normal file
@ -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()
|
||||
106
d2ypp2/tools/query_host03_youtube_events.py
Normal file
106
d2ypp2/tools/query_host03_youtube_events.py
Normal file
@ -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())
|
||||
42
d2ypp2/tools/read_host03_youtube_log.py
Normal file
42
d2ypp2/tools/read_host03_youtube_log.py
Normal file
@ -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"))
|
||||
42
d2ypp2/tools/read_host03_youtube_log_probe.py
Normal file
42
d2ypp2/tools/read_host03_youtube_log_probe.py
Normal file
@ -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"))
|
||||
109
d2ypp2/tools/restart_all_youtube_lanes.py
Normal file
109
d2ypp2/tools/restart_all_youtube_lanes.py
Normal file
@ -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()
|
||||
79
d2ypp2/tools/run_stop_optional_hosts.py
Normal file
79
d2ypp2/tools/run_stop_optional_hosts.py
Normal file
@ -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()
|
||||
95
d2ypp2/tools/upload_console_out_host03.py
Normal file
95
d2ypp2/tools/upload_console_out_host03.py
Normal file
@ -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())
|
||||
51
d2ypp2/tools/verify_relay_log_host03.py
Normal file
51
d2ypp2/tools/verify_relay_log_host03.py
Normal file
@ -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())
|
||||
3
d2ypp2/web-console/app/youtube-relay-log/page.tsx
Normal file
3
d2ypp2/web-console/app/youtube-relay-log/page.tsx
Normal file
@ -0,0 +1,3 @@
|
||||
"use client";
|
||||
|
||||
export { default } from "@/components/live-product/LiveYoutubeRelayLogView";
|
||||
@ -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}
|
||||
|
||||
@ -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<string>("");
|
||||
const [recentLog, setRecentLog] = useState("");
|
||||
@ -452,7 +455,7 @@ export function LiveProcessLiveLogCard({
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h3 className="text-sm font-semibold text-white">{t("当前直播日志", "Live process log")}</h3>
|
||||
{pushingNow ? (
|
||||
{pushingNow && !hideStatusOverview ? (
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-500/15 px-2.5 py-0.5 text-[10px] font-medium text-emerald-100 ring-1 ring-emerald-500/25">
|
||||
<span className="relative flex h-2 w-2">
|
||||
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-70" />
|
||||
@ -492,6 +495,7 @@ export function LiveProcessLiveLogCard({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!hideStatusOverview ? (
|
||||
<div className="mt-4 space-y-3 rounded-xl border border-white/[0.06] bg-black/25 p-4">
|
||||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<div className="rounded-lg border border-white/[0.05] bg-black/20 p-3">
|
||||
@ -646,6 +650,7 @@ export function LiveProcessLiveLogCard({
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{processStatus !== "not_found" && processStatus !== "invalid" ? (
|
||||
<div className="mt-4 grid gap-4 lg:grid-cols-2">
|
||||
|
||||
@ -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<string, unknown>;
|
||||
};
|
||||
|
||||
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<Lang>(() => {
|
||||
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<RelaySession[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [selected, setSelected] = useState<RelaySession | null>(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 (
|
||||
<div className="min-h-screen bg-zinc-950 text-zinc-100">
|
||||
<div className="mx-auto max-w-7xl px-4 py-6 sm:px-6">
|
||||
<div className="mb-6 flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">{t("YouTube 推流日志", "YouTube relay log")}</h1>
|
||||
<p className="mt-1 max-w-3xl text-sm text-zinc-400">
|
||||
{t(
|
||||
"记录每次抖音源转播到 YouTube 的时段、主播昵称、直播间 URL 与开播截图,便于追溯音乐版权等问题。",
|
||||
"Track each Douyin-to-YouTube relay with anchor, room URL, timing, and start snapshot for copyright tracing.",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void loadSessions()}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10 disabled:opacity-50"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||||
{t("刷新", "Refresh")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void importLogs()}
|
||||
disabled={importing}
|
||||
className="inline-flex items-center gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-100 hover:bg-amber-500/20 disabled:opacity-50"
|
||||
>
|
||||
{importing ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
|
||||
{t("从 PM2 日志导入历史", "Import history from PM2 log")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-2 xl:grid-cols-6">
|
||||
<label className="block text-xs text-zinc-400 xl:col-span-1">
|
||||
{t("线路 / 进程", "Lane / process")}
|
||||
<input
|
||||
value={process}
|
||||
onChange={(e) => {
|
||||
setOffset(0);
|
||||
setProcess(e.target.value);
|
||||
}}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-zinc-900 px-3 py-2 text-sm"
|
||||
placeholder="youtube"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-xs text-zinc-400 xl:col-span-2">
|
||||
{t("检索(昵称 / URL / 房间号)", "Search nickname / URL / room id")}
|
||||
<div className="relative mt-1">
|
||||
<Search className="pointer-events-none absolute left-3 top-2.5 h-4 w-4 text-zinc-500" />
|
||||
<input
|
||||
value={q}
|
||||
onChange={(e) => {
|
||||
setOffset(0);
|
||||
setQ(e.target.value);
|
||||
}}
|
||||
className="w-full rounded-lg border border-white/10 bg-zinc-900 py-2 pl-9 pr-3 text-sm"
|
||||
placeholder={t("例如:柠檬茶、745277409780", "e.g. lemon tea, room id")}
|
||||
/>
|
||||
</div>
|
||||
</label>
|
||||
<label className="block text-xs text-zinc-400">
|
||||
{t("开始日期", "From date")}
|
||||
<input
|
||||
type="date"
|
||||
value={dateFrom}
|
||||
onChange={(e) => {
|
||||
setOffset(0);
|
||||
setDateFrom(e.target.value);
|
||||
}}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-zinc-900 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-xs text-zinc-400">
|
||||
{t("结束日期", "To date")}
|
||||
<input
|
||||
type="date"
|
||||
value={dateTo}
|
||||
onChange={(e) => {
|
||||
setOffset(0);
|
||||
setDateTo(e.target.value);
|
||||
}}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-zinc-900 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-xs text-zinc-400">
|
||||
{t("状态", "Status")}
|
||||
<select
|
||||
value={status}
|
||||
onChange={(e) => {
|
||||
setOffset(0);
|
||||
setStatus(e.target.value);
|
||||
}}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-zinc-900 px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">{t("全部", "All")}</option>
|
||||
<option value="active">{t("进行中", "Active")}</option>
|
||||
<option value="ended">{t("已结束", "Ended")}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm text-rose-100">{error}</div> : null}
|
||||
|
||||
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full text-left text-sm">
|
||||
<thead className="bg-white/5 text-xs uppercase tracking-wide text-zinc-400">
|
||||
<tr>
|
||||
<th className="px-3 py-3">{t("截图", "Cover")}</th>
|
||||
<th className="px-3 py-3">{t("主播昵称", "Anchor")}</th>
|
||||
<th className="px-3 py-3">{t("直播间 URL", "Room URL")}</th>
|
||||
<th className="px-3 py-3">{t("推流开始", "Started")}</th>
|
||||
<th className="px-3 py-3">{t("推流结束", "Ended")}</th>
|
||||
<th className="px-3 py-3">{t("总时长", "Duration")}</th>
|
||||
<th className="px-3 py-3">{t("推流日期", "Date")}</th>
|
||||
<th className="px-3 py-3">{t("YT 密钥", "YT key")}</th>
|
||||
<th className="px-3 py-3">{t("线路", "Lane")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sessions.map((session) => {
|
||||
const url = douyinUrl(session);
|
||||
return (
|
||||
<tr
|
||||
key={session.id}
|
||||
className="cursor-pointer border-t border-white/5 hover:bg-white/[0.03]"
|
||||
onClick={() => setSelected(session)}
|
||||
>
|
||||
<td className="px-3 py-3">
|
||||
{session.cover_url ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={`${session.cover_url}?ts=${session.started_at || 0}`}
|
||||
alt={session.anchor_name || "cover"}
|
||||
className="h-16 w-10 rounded object-cover ring-1 ring-white/10"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-16 w-10 items-center justify-center rounded bg-zinc-900 text-[10px] text-zinc-500 ring-1 ring-white/10">
|
||||
N/A
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-3 font-medium text-zinc-100">{session.anchor_name || "—"}</td>
|
||||
<td className="max-w-[14rem] truncate px-3 py-3 font-mono text-xs text-cyan-300/90">
|
||||
{url ? (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="hover:underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{url.replace(/^https?:\/\//, "")}
|
||||
</a>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-3 text-zinc-300">{fmtTs(session.started_at, lang)}</td>
|
||||
<td className="whitespace-nowrap px-3 py-3 text-zinc-300">
|
||||
{session.ended_at ? fmtTs(session.ended_at, lang) : t("进行中", "Active")}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-3 font-mono text-zinc-200">
|
||||
{fmtDuration(session.duration_seconds, lang)}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-3">{session.push_date || "—"}</td>
|
||||
<td className="whitespace-nowrap px-3 py-3 font-mono text-xs text-amber-200/90">
|
||||
{session.youtube_key_suffix ? `…${session.youtube_key_suffix}` : "—"}
|
||||
</td>
|
||||
<td className="px-3 py-3 text-xs text-zinc-400">
|
||||
{session.channel_name || session.process || "—"}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
{!loading && sessions.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={9} className="px-3 py-10 text-center text-zinc-500">
|
||||
{t("暂无推流记录。可先点击「从 PM2 日志导入历史」。", "No relay sessions yet. Try importing PM2 logs first.")}
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex items-center justify-between text-sm text-zinc-400">
|
||||
<span>
|
||||
{t("共", "Total")} {total} {t("条", "records")} · {t("第", "Page")} {pageIndex}/{pageCount}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={offset <= 0 || loading}
|
||||
onClick={() => setOffset(Math.max(0, offset - limit))}
|
||||
className="rounded-lg border border-white/10 px-3 py-1.5 disabled:opacity-40"
|
||||
>
|
||||
{t("上一页", "Prev")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={offset + limit >= total || loading}
|
||||
onClick={() => setOffset(offset + limit)}
|
||||
className="rounded-lg border border-white/10 px-3 py-1.5 disabled:opacity-40"
|
||||
>
|
||||
{t("下一页", "Next")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selected ? (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
|
||||
onClick={() => setSelected(null)}
|
||||
>
|
||||
<div
|
||||
className="max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-2xl border border-white/10 bg-zinc-950 p-5 shadow-2xl"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">{selected.anchor_name || t("推流详情", "Relay detail")}</h2>
|
||||
<p className="mt-1 text-sm text-zinc-400">{selected.stream_title || "—"}</p>
|
||||
</div>
|
||||
<button type="button" className="text-zinc-400 hover:text-zinc-200" onClick={() => setSelected(null)}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-[8rem_1fr]">
|
||||
{selected.cover_url ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={`${selected.cover_url}?ts=${selected.started_at || 0}`}
|
||||
alt={selected.anchor_name || "cover"}
|
||||
className="h-36 w-full rounded-lg object-cover ring-1 ring-white/10"
|
||||
/>
|
||||
) : null}
|
||||
<dl className="grid gap-2 text-sm">
|
||||
<div>
|
||||
<dt className="text-zinc-500">{t("直播间 URL", "Room URL")}</dt>
|
||||
<dd className="break-all font-mono text-cyan-300">
|
||||
{douyinUrl(selected) ? (
|
||||
<a href={douyinUrl(selected)} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 hover:underline">
|
||||
{douyinUrl(selected)} <ExternalLink className="h-3.5 w-3.5" />
|
||||
</a>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-zinc-500">{t("房间号", "Room id")}</dt>
|
||||
<dd>{selected.source_room_id || "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-zinc-500">{t("推流开始", "Started")}</dt>
|
||||
<dd>{fmtTs(selected.started_at, lang)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-zinc-500">{t("推流结束", "Ended")}</dt>
|
||||
<dd>{selected.ended_at ? fmtTs(selected.ended_at, lang) : t("进行中", "Active")}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-zinc-500">{t("总时长", "Duration")}</dt>
|
||||
<dd>{fmtDuration(selected.duration_seconds, lang)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-zinc-500">{t("推流日期", "Push date")}</dt>
|
||||
<dd>{selected.push_date || "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-zinc-500">{t("线路 / 进程", "Lane / process")}</dt>
|
||||
<dd>
|
||||
{selected.channel_name ? `${selected.channel_name} · ` : ""}
|
||||
{selected.process || "—"}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-zinc-500">{t("结束原因", "End reason")}</dt>
|
||||
<dd>{selected.end_reason || "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-zinc-500">{t("YouTube 推流密钥(后6位)", "YouTube stream key (last 6)")}</dt>
|
||||
<dd className="font-mono">{selected.youtube_key_suffix ? `…${selected.youtube_key_suffix}` : "—"}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LiveYoutubeRelayLogView;
|
||||
@ -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<string, P
|
||||
|
||||
function isLivePushingRow(row?: LiveProcRow): boolean {
|
||||
const business = (row?.business_status || "").trim().toLowerCase();
|
||||
return (
|
||||
!!row?.is_pushing ||
|
||||
business === "streaming" ||
|
||||
business === "relay_slow" ||
|
||||
business === "source_stalled"
|
||||
);
|
||||
return !!row?.is_pushing || business === "streaming" || business === "relay_starting";
|
||||
}
|
||||
|
||||
function procStartBlocked(row?: LiveProcRow): boolean {
|
||||
return isLivePushingRow(row);
|
||||
}
|
||||
|
||||
function proLaneStatusLabel(row: LiveProcRow | undefined, t: TFn): string {
|
||||
const business = (row?.business_status || "").trim().toLowerCase();
|
||||
if (
|
||||
business === "source_stalled" ||
|
||||
business === "relay_slow" ||
|
||||
business === "waiting_source" ||
|
||||
business === "source_live"
|
||||
) {
|
||||
return businessStatusLabel(row, t);
|
||||
}
|
||||
if (isLivePushingRow(row)) return t("推流中", "Pushing");
|
||||
return businessStatusLabel(row, t);
|
||||
}
|
||||
@ -413,6 +424,12 @@ function pm2StatusOnline(st?: string) {
|
||||
return /^(online|running)$/i.test((st || "").trim());
|
||||
}
|
||||
|
||||
function openRelayLogPage(process: string) {
|
||||
const proc = (process || "youtube").trim() || "youtube";
|
||||
const url = `/youtube-relay-log?process=${encodeURIComponent(proc)}`;
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
}
|
||||
|
||||
function businessStatusLabel(row: LiveProcRow | undefined, t: TFn): string {
|
||||
const business = (row?.business_status || "").trim().toLowerCase();
|
||||
if (business === "ready") return t("已配置", "Ready");
|
||||
@ -651,6 +668,7 @@ function LiveStreamActionBtn({
|
||||
targetPm2,
|
||||
busy,
|
||||
online,
|
||||
pushing,
|
||||
label,
|
||||
className,
|
||||
baseLock,
|
||||
@ -664,6 +682,7 @@ function LiveStreamActionBtn({
|
||||
targetPm2: string;
|
||||
busy: string | null;
|
||||
online: boolean;
|
||||
pushing: boolean;
|
||||
label: string;
|
||||
className: string;
|
||||
baseLock: boolean;
|
||||
@ -677,7 +696,7 @@ function LiveStreamActionBtn({
|
||||
const actionForBusy = busyKind ?? kind;
|
||||
const loading = !!(forThisProc && pb.action === actionForBusy);
|
||||
const siblingBusy = !!(forThisProc && pb.action !== actionForBusy);
|
||||
const blockStart = kind === "start" && online;
|
||||
const blockStart = kind === "start" && pushing;
|
||||
const blockStop = kind === "stop" && !online;
|
||||
const blockRestart = kind === "restart" && !online;
|
||||
const blocked = blockStart || blockStop || blockRestart;
|
||||
@ -690,7 +709,7 @@ function LiveStreamActionBtn({
|
||||
return;
|
||||
}
|
||||
if (blockStart) {
|
||||
notify(t("已在直播中,无需重复开始", "Already live"));
|
||||
notify(t("已在推流中,无需重复开始", "Already pushing"));
|
||||
return;
|
||||
}
|
||||
if (blockStop) {
|
||||
@ -1958,6 +1977,7 @@ export function LiveYoutubeUnmannedView({
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
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({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-3">
|
||||
<div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
|
||||
<LiveStreamActionBtn
|
||||
kind="start"
|
||||
targetPm2={singleRuntimeProc}
|
||||
busy={busy}
|
||||
online={singleOnline}
|
||||
pushing={singlePushing}
|
||||
label={t("开始直播", "Start")}
|
||||
className="bg-emerald-500/20 text-emerald-200 ring-emerald-500/30"
|
||||
baseLock={false}
|
||||
@ -3154,6 +3177,7 @@ export function LiveYoutubeUnmannedView({
|
||||
targetPm2={singleRuntimeProc}
|
||||
busy={busy}
|
||||
online={singleOnline}
|
||||
pushing={singlePushing}
|
||||
label={t("停止直播", "Stop")}
|
||||
className="bg-rose-500/15 text-rose-200 ring-rose-500/25"
|
||||
baseLock={false}
|
||||
@ -3166,6 +3190,7 @@ export function LiveYoutubeUnmannedView({
|
||||
targetPm2={singleRuntimeProc}
|
||||
busy={busy}
|
||||
online={singleOnline}
|
||||
pushing={singlePushing}
|
||||
label={t("重新开始", "Restart")}
|
||||
className="bg-amber-500/15 text-amber-200 ring-amber-500/25"
|
||||
baseLock={false}
|
||||
@ -3173,6 +3198,15 @@ export function LiveYoutubeUnmannedView({
|
||||
notify={notify}
|
||||
t={t}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openRelayLogPage(singleRuntimeProc)}
|
||||
className="inline-flex min-h-[2.75rem] items-center justify-center gap-1.5 rounded-xl bg-violet-500/15 px-3 py-2 text-sm font-medium text-violet-100 ring-1 ring-violet-500/25 transition hover:bg-violet-500/25"
|
||||
title={t("打开推流日志(新标签页)", "Open relay log in a new tab")}
|
||||
>
|
||||
<ScrollText className="h-4 w-4 shrink-0" aria-hidden />
|
||||
{t("日志", "Log")}
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-center justify-center gap-2 text-xs">
|
||||
<span className={`rounded-full px-2.5 py-0.5 font-medium ring-1 ${businessStatusBadgeClass(singleRow)}`}>
|
||||
@ -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
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openRelayLogPage(pm)}
|
||||
className="inline-flex min-h-[2rem] items-center justify-center gap-1 rounded-lg border border-violet-500/25 bg-violet-500/10 px-2.5 py-1.5 text-violet-100 ring-1 ring-violet-500/20 transition hover:bg-violet-500/20"
|
||||
title={t("打开推流日志(新标签页)", "Open relay log in a new tab")}
|
||||
>
|
||||
<ScrollText className="h-3.5 w-3.5 shrink-0" aria-hidden />
|
||||
{t("日志", "Log")}
|
||||
</button>
|
||||
{laneNeko ? (
|
||||
<button
|
||||
type="button"
|
||||
@ -3390,18 +3437,21 @@ export function LiveYoutubeUnmannedView({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<LiveProcessLiveLogCard
|
||||
t={t}
|
||||
currentProc={runtimeLogProc}
|
||||
fetchJson={fetchJson}
|
||||
urlListText={monitorUrlDraft}
|
||||
keySuffixUi={keySuffixUi}
|
||||
showKeyRow
|
||||
pollMs={statusCardPollMs}
|
||||
refreshToken={activeViewRefreshToken}
|
||||
monitorRow={overviewRow ?? undefined}
|
||||
preferredTitle={mode === "pro" ? overviewLaneName : undefined}
|
||||
/>
|
||||
{!HIDE_YOUTUBE_LIVE_PROCESS_LOG ? (
|
||||
<LiveProcessLiveLogCard
|
||||
t={t}
|
||||
currentProc={runtimeLogProc}
|
||||
fetchJson={fetchJson}
|
||||
urlListText={monitorUrlDraft}
|
||||
keySuffixUi={keySuffixUi}
|
||||
showKeyRow={false}
|
||||
hideStatusOverview
|
||||
pollMs={statusCardPollMs}
|
||||
refreshToken={activeViewRefreshToken}
|
||||
monitorRow={overviewRow ?? undefined}
|
||||
preferredTitle={mode === "pro" ? overviewLaneName : undefined}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{!HIDE_YOUTUBE_QUALITY_GUARD ? qualityGuardPanel : null}
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -1 +1 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{7042:function(e,a,_){Promise.resolve().then(_.t.bind(_,2641,23)),Promise.resolve().then(_.t.bind(_,13,23)),Promise.resolve().then(_.t.bind(_,4443,23))},4443:function(){},13:function(e){e.exports={style:{fontFamily:"'__geistMono_c3aa02', '__geistMono_Fallback_c3aa02'"},className:"__className_c3aa02",variable:"__variable_c3aa02"}},2641:function(e){e.exports={style:{fontFamily:"'__geistSans_1e4310', '__geistSans_Fallback_1e4310'"},className:"__className_1e4310",variable:"__variable_1e4310"}}},function(e){e.O(0,[515,649,945,744],function(){return e(e.s=7042)}),_N_E=e.O()}]);
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{7042:function(e,a,_){Promise.resolve().then(_.t.bind(_,2641,23)),Promise.resolve().then(_.t.bind(_,13,23)),Promise.resolve().then(_.t.bind(_,4443,23))},4443:function(){},13:function(e){e.exports={style:{fontFamily:"'__geistMono_c3aa02', '__geistMono_Fallback_c3aa02'"},className:"__className_c3aa02",variable:"__variable_c3aa02"}},2641:function(e){e.exports={style:{fontFamily:"'__geistSans_1e4310', '__geistSans_Fallback_1e4310'"},className:"__className_1e4310",variable:"__variable_1e4310"}}},function(e){e.O(0,[814,824,649,945,744],function(){return e(e.s=7042)}),_N_E=e.O()}]);
|
||||
@ -1 +1 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{618:function(n,e,u){Promise.resolve().then(u.bind(u,3372))},3372:function(n,e,u){"use strict";u.r(e),u.d(e,{default:function(){return t.Z}});var t=u(3371)}},function(n){n.O(0,[335,993,653,371,649,945,744],function(){return n(n.s=618)}),_N_E=n.O()}]);
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{618:function(n,e,u){Promise.resolve().then(u.bind(u,3372))},3372:function(n,e,u){"use strict";u.r(e),u.d(e,{default:function(){return t.Z}});var t=u(3371)}},function(n){n.O(0,[335,270,653,371,649,945,744],function(){return n(n.s=618)}),_N_E=n.O()}]);
|
||||
@ -1 +1 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[851],{6870:function(n,e,u){Promise.resolve().then(u.bind(u,8307))},8307:function(n,e,u){"use strict";u.r(e),u.d(e,{default:function(){return t.Z}});var t=u(3371)}},function(n){n.O(0,[335,993,653,371,649,945,744],function(){return n(n.s=6870)}),_N_E=n.O()}]);
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[851],{6870:function(n,e,u){Promise.resolve().then(u.bind(u,8307))},8307:function(n,e,u){"use strict";u.r(e),u.d(e,{default:function(){return t.Z}});var t=u(3371)}},function(n){n.O(0,[335,270,653,371,649,945,744],function(){return n(n.s=6870)}),_N_E=n.O()}]);
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -1 +1 @@
|
||||
!function(){"use strict";var e,t,n,r,o,u,i,c,f,a={},l={};function s(e){var t=l[e];if(void 0!==t)return t.exports;var n=l[e]={exports:{}},r=!0;try{a[e](n,n.exports,s),r=!1}finally{r&&delete l[e]}return n.exports}s.m=a,e=[],s.O=function(t,n,r,o){if(n){o=o||0;for(var u=e.length;u>0&&e[u-1][2]>o;u--)e[u]=e[u-1];e[u]=[n,r,o];return}for(var i=1/0,u=0;u<e.length;u++){for(var n=e[u][0],r=e[u][1],o=e[u][2],c=!0,f=0;f<n.length;f++)i>=o&&Object.keys(s.O).every(function(e){return s.O[e](n[f])})?n.splice(f--,1):(c=!1,o<i&&(i=o));if(c){e.splice(u--,1);var a=r();void 0!==a&&(t=a)}}return t},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,{a:t}),t},n=Object.getPrototypeOf?function(e){return Object.getPrototypeOf(e)}:function(e){return e.__proto__},s.t=function(e,r){if(1&r&&(e=this(e)),8&r||"object"==typeof e&&e&&(4&r&&e.__esModule||16&r&&"function"==typeof e.then))return e;var o=Object.create(null);s.r(o);var u={};t=t||[null,n({}),n([]),n(n)];for(var i=2&r&&e;"object"==typeof i&&!~t.indexOf(i);i=n(i))Object.getOwnPropertyNames(i).forEach(function(t){u[t]=function(){return e[t]}});return u.default=function(){return e},s.d(o,u),o},s.d=function(e,t){for(var n in t)s.o(t,n)&&!s.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},s.f={},s.e=function(e){return Promise.all(Object.keys(s.f).reduce(function(t,n){return s.f[n](e,t),t},[]))},s.u=function(e){return"static/chunks/"+(467===e?"198f8915":e)+"."+({214:"86fe6f7fb2f5906b",467:"30d124d46046bb3d"})[e]+".js"},s.miniCssF=function(e){},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r={},o="_N_E:",s.l=function(e,t,n,u){if(r[e]){r[e].push(t);return}if(void 0!==n)for(var i,c,f=document.getElementsByTagName("script"),a=0;a<f.length;a++){var l=f[a];if(l.getAttribute("src")==e||l.getAttribute("data-webpack")==o+n){i=l;break}}i||(c=!0,(i=document.createElement("script")).charset="utf-8",i.timeout=120,s.nc&&i.setAttribute("nonce",s.nc),i.setAttribute("data-webpack",o+n),i.src=s.tu(e)),r[e]=[t];var d=function(t,n){i.onerror=i.onload=null,clearTimeout(p);var o=r[e];if(delete r[e],i.parentNode&&i.parentNode.removeChild(i),o&&o.forEach(function(e){return e(n)}),t)return t(n)},p=setTimeout(d.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=d.bind(null,i.onerror),i.onload=d.bind(null,i.onload),c&&document.head.appendChild(i)},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.tt=function(){return void 0===u&&(u={createScriptURL:function(e){return e}},"undefined"!=typeof trustedTypes&&trustedTypes.createPolicy&&(u=trustedTypes.createPolicy("nextjs#bundler",u))),u},s.tu=function(e){return s.tt().createScriptURL(e)},s.p="/_next/",i={272:0,515:0},s.f.j=function(e,t){var n=s.o(i,e)?i[e]:void 0;if(0!==n){if(n)t.push(n[2]);else if(/^(272|515)$/.test(e))i[e]=0;else{var r=new Promise(function(t,r){n=i[e]=[t,r]});t.push(n[2]=r);var o=s.p+s.u(e),u=Error();s.l(o,function(t){if(s.o(i,e)&&(0!==(n=i[e])&&(i[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),o=t&&t.target&&t.target.src;u.message="Loading chunk "+e+" failed.\n("+r+": "+o+")",u.name="ChunkLoadError",u.type=r,u.request=o,n[1](u)}},"chunk-"+e,e)}}},s.O.j=function(e){return 0===i[e]},c=function(e,t){var n,r,o=t[0],u=t[1],c=t[2],f=0;if(o.some(function(e){return 0!==i[e]})){for(n in u)s.o(u,n)&&(s.m[n]=u[n]);if(c)var a=c(s)}for(e&&e(t);f<o.length;f++)r=o[f],s.o(i,r)&&i[r]&&i[r][0](),i[r]=0;return s.O(a)},(f=self.webpackChunk_N_E=self.webpackChunk_N_E||[]).forEach(c.bind(null,0)),f.push=c.bind(null,f.push.bind(f))}();
|
||||
!function(){"use strict";var e,t,n,r,o,u,i,c,f,a={},l={};function s(e){var t=l[e];if(void 0!==t)return t.exports;var n=l[e]={exports:{}},r=!0;try{a[e](n,n.exports,s),r=!1}finally{r&&delete l[e]}return n.exports}s.m=a,e=[],s.O=function(t,n,r,o){if(n){o=o||0;for(var u=e.length;u>0&&e[u-1][2]>o;u--)e[u]=e[u-1];e[u]=[n,r,o];return}for(var i=1/0,u=0;u<e.length;u++){for(var n=e[u][0],r=e[u][1],o=e[u][2],c=!0,f=0;f<n.length;f++)i>=o&&Object.keys(s.O).every(function(e){return s.O[e](n[f])})?n.splice(f--,1):(c=!1,o<i&&(i=o));if(c){e.splice(u--,1);var a=r();void 0!==a&&(t=a)}}return t},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,{a:t}),t},n=Object.getPrototypeOf?function(e){return Object.getPrototypeOf(e)}:function(e){return e.__proto__},s.t=function(e,r){if(1&r&&(e=this(e)),8&r||"object"==typeof e&&e&&(4&r&&e.__esModule||16&r&&"function"==typeof e.then))return e;var o=Object.create(null);s.r(o);var u={};t=t||[null,n({}),n([]),n(n)];for(var i=2&r&&e;"object"==typeof i&&!~t.indexOf(i);i=n(i))Object.getOwnPropertyNames(i).forEach(function(t){u[t]=function(){return e[t]}});return u.default=function(){return e},s.d(o,u),o},s.d=function(e,t){for(var n in t)s.o(t,n)&&!s.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},s.f={},s.e=function(e){return Promise.all(Object.keys(s.f).reduce(function(t,n){return s.f[n](e,t),t},[]))},s.u=function(e){return"static/chunks/"+(467===e?"198f8915":e)+"."+({214:"86fe6f7fb2f5906b",467:"30d124d46046bb3d"})[e]+".js"},s.miniCssF=function(e){},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r={},o="_N_E:",s.l=function(e,t,n,u){if(r[e]){r[e].push(t);return}if(void 0!==n)for(var i,c,f=document.getElementsByTagName("script"),a=0;a<f.length;a++){var l=f[a];if(l.getAttribute("src")==e||l.getAttribute("data-webpack")==o+n){i=l;break}}i||(c=!0,(i=document.createElement("script")).charset="utf-8",i.timeout=120,s.nc&&i.setAttribute("nonce",s.nc),i.setAttribute("data-webpack",o+n),i.src=s.tu(e)),r[e]=[t];var d=function(t,n){i.onerror=i.onload=null,clearTimeout(p);var o=r[e];if(delete r[e],i.parentNode&&i.parentNode.removeChild(i),o&&o.forEach(function(e){return e(n)}),t)return t(n)},p=setTimeout(d.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=d.bind(null,i.onerror),i.onload=d.bind(null,i.onload),c&&document.head.appendChild(i)},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.tt=function(){return void 0===u&&(u={createScriptURL:function(e){return e}},"undefined"!=typeof trustedTypes&&trustedTypes.createPolicy&&(u=trustedTypes.createPolicy("nextjs#bundler",u))),u},s.tu=function(e){return s.tt().createScriptURL(e)},s.p="/_next/",i={272:0,814:0,824:0},s.f.j=function(e,t){var n=s.o(i,e)?i[e]:void 0;if(0!==n){if(n)t.push(n[2]);else if(/^(272|814|824)$/.test(e))i[e]=0;else{var r=new Promise(function(t,r){n=i[e]=[t,r]});t.push(n[2]=r);var o=s.p+s.u(e),u=Error();s.l(o,function(t){if(s.o(i,e)&&(0!==(n=i[e])&&(i[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),o=t&&t.target&&t.target.src;u.message="Loading chunk "+e+" failed.\n("+r+": "+o+")",u.name="ChunkLoadError",u.type=r,u.request=o,n[1](u)}},"chunk-"+e,e)}}},s.O.j=function(e){return 0===i[e]},c=function(e,t){var n,r,o=t[0],u=t[1],c=t[2],f=0;if(o.some(function(e){return 0!==i[e]})){for(n in u)s.o(u,n)&&(s.m[n]=u[n]);if(c)var a=c(s)}for(e&&e(t);f<o.length;f++)r=o[f],s.o(i,r)&&i[r]&&i[r][0](),i[r]=0;return s.O(a)},(f=self.webpackChunk_N_E=self.webpackChunk_N_E||[]).forEach(c.bind(null,0)),f.push=c.bind(null,f.push.bind(f))}();
|
||||
@ -0,0 +1 @@
|
||||
@font-face{font-family:__geistSans_1e4310;src:url(/_next/static/media/4473ecc91f70f139-s.p.woff) format("woff");font-display:swap;font-weight:100 900}@font-face{font-family:__geistSans_Fallback_1e4310;src:local("Arial");ascent-override:85.83%;descent-override:20.52%;line-gap-override:9.33%;size-adjust:107.19%}.__className_1e4310{font-family:__geistSans_1e4310,__geistSans_Fallback_1e4310}.__variable_1e4310{--font-geist-sans:"__geistSans_1e4310","__geistSans_Fallback_1e4310"}@font-face{font-family:__geistMono_c3aa02;src:url(/_next/static/media/463dafcda517f24f-s.p.woff) format("woff");font-display:swap;font-weight:100 900}@font-face{font-family:__geistMono_Fallback_c3aa02;src:local("Arial");ascent-override:69.97%;descent-override:16.73%;line-gap-override:7.61%;size-adjust:131.49%}.__className_c3aa02{font-family:__geistMono_c3aa02,__geistMono_Fallback_c3aa02}.__variable_c3aa02{--font-geist-mono:"__geistMono_c3aa02","__geistMono_Fallback_c3aa02"}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -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
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -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
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -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
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -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
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -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
|
||||
|
||||
1
d2ypp2/web-console/out/youtube-relay-log.html
Normal file
1
d2ypp2/web-console/out/youtube-relay-log.html
Normal file
File diff suppressed because one or more lines are too long
7
d2ypp2/web-console/out/youtube-relay-log.txt
Normal file
7
d2ypp2/web-console/out/youtube-relay-log.txt
Normal file
@ -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
|
||||
@ -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")
|
||||
|
||||
@ -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:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user