Compare commits
No commits in common. "3bc2cf6a1e5792cd3ef9b0ee81e400d6c4d1a182" and "fe577c6536dc6a91d494797a4bef2a32bd08812d" have entirely different histories.
3bc2cf6a1e
...
fe577c6536
@ -6,9 +6,9 @@
|
||||
|
||||
### 核心能力
|
||||
|
||||
- 抖音直播间 → YouTube Live:**控制台默认多频道 Pro**(每条线路独立 `youtube.ini`、`URL_config` 与 PM2 进程);单频道模式仍保留在代码中,UI 切换已隐藏
|
||||
- 抖音直播间 → YouTube Live:支持单频道 / 多频道同时推流,每个任务独立 `youtube.ini`、`URL_config` 与 PM2 进程
|
||||
- TikTok 直播:支持视频流转发到硬件 HDMI,也可配合 SRS / OBS 接流后再转发
|
||||
- Neko 浏览器:默认个人管理员模式,不挂 Chrome 企业策略、不禁用 Google Sync;保留管理员会话、开发者工具与 Tampermonkey 持久化;按 `NEKO_INSTANCE_COUNT` 动态生成独立容器,默认保底 2 个,YouTube PRO 频道保存会自动提升容量;**WireGuard 上线后安装脚本自动持久化 `NEKO_ACCESS_MODE=remote` 与 overlay `NAT1TO1`,并放行 WebRTC 端口**;直连失败时 Neko 默认走 ShellCrash `:7890`,仅在 proxycheap 实测可用时才自动开启 `:7894`
|
||||
- Neko 浏览器:默认个人管理员模式,不挂 Chrome 企业策略、不禁用 Google Sync;保留管理员会话、开发者工具与 Tampermonkey 持久化;按 `NEKO_INSTANCE_COUNT` 动态生成独立容器,默认保底 2 个,YouTube PRO 频道保存会自动提升容量
|
||||
- 兼容架构:Linux `x86_64` / `arm64`,使用一键脚本部署,控制面板默认域名 `live.local`
|
||||
|
||||
## Linux Unmanned Live Profiles
|
||||
|
||||
@ -41,36 +41,14 @@ SHELLCRASH_ATTACH_FFMPEG=auto
|
||||
# Docker bridge CIDR allowed to reach ShellCrash listeners. This keeps Neko
|
||||
# transparent mode working when the browser proxy switch is off and UFW denies INPUT.
|
||||
SHELLCRASH_DOCKER_CIDR=172.16.0.0/12
|
||||
# WireGuard overlay used by the project.
|
||||
# Some fleets use 10.88.0.0/24; 腾讯云中继 commonly uses 10.66.66.0/24.
|
||||
SHELLCRASH_WG_CIDR=10.66.66.0/24
|
||||
# Optional override (comma-separated). Empty = Docker + WG overlays + RFC1918 defaults
|
||||
# (includes both 10.66.66.0/24 and 10.88.0.0/24 so dashboard :9999 works over either tunnel).
|
||||
# SHELLCRASH_TRUSTED_CIDRS=172.16.0.0/12,10.66.66.0/24,10.88.0.0/24,192.168.0.0/16,10.0.0.0/8
|
||||
# Optional install-time HTTP(S) proxy (e.g. Windows Clash http://192.168.21.36:7897).
|
||||
# Leave empty for direct. When set, installer also writes apt + Docker daemon proxy drop-ins
|
||||
# so image pulls work (Docker does not inherit shell http_proxy). Clear after install if desired.
|
||||
# LIVE_HTTP_PROXY=
|
||||
# LIVE_HTTPS_PROXY=
|
||||
# LIVE_NO_PROXY=localhost,127.0.0.1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,*.lan,*.local
|
||||
# Neko 浏览器代理总开关(proxycheap 静态住宅 IP,默认端口 7894)。
|
||||
# 仅当宿主机本身无法直连 Google/YouTube 时,Neko 才走 ShellCrash:
|
||||
# - 开关 ON -> proxycheap 专用 listener(NEKO_SHELLCRASH_PROXY_PORT,默认 7894)
|
||||
# - 开关 OFF -> ShellCrash 主 mixed 口(7890),仍翻墙,不走 proxycheap
|
||||
# 若宿主机已有软路由/可直连外网,Neko 始终直连,不受此开关影响。
|
||||
# Neko 浏览器 HTTP 代理总开关;默认 0=关闭(走宿主机/软路由直连)。
|
||||
# 当直连 Google/YouTube 失败且 ShellCrash 代理可用时,控制台/启动脚本会自动设为 1(除非 NEKO_BROWSER_PROXY_MANUAL=1)。
|
||||
ENABLE_NEKO_BROWSER_PROXY=0
|
||||
# 用户在控制台手动切换 Neko 代理后设为 1,阻止自动开关覆盖手动选择。
|
||||
# NEKO_BROWSER_PROXY_MANUAL=0
|
||||
# Neko 专用 ShellCrash mixed listener(proxycheap 静态住宅 IP;仅直连失败且开关 ON 时生效)
|
||||
# Neko 专用 ShellCrash mixed listener(与 FFmpeg 的 7890/tuic3 出口隔离;仅 ENABLE_NEKO_BROWSER_PROXY=1 时生效)
|
||||
NEKO_SHELLCRASH_PROXY_PORT=7894
|
||||
SHELLCRASH_NEKO_PROXY_NODE=proxycheap
|
||||
# 多开 Neko 时务必给每条线路独立出口,否则 Google 会把同 IP 第二账号登录判为“登录取消”。
|
||||
# 仅当 NEKO_BROWSER_PROXY_PER_INSTANCE=1 且 proxycheap 开关 ON 时,实例 2/3... 才会使用独立端口。
|
||||
# NEKO_BROWSER_PROXY_PER_INSTANCE=1
|
||||
# 方式 B:显式指定(推荐)
|
||||
# NEKO_SHELLCRASH_PROXY_PORT_1=7894
|
||||
# NEKO_SHELLCRASH_PROXY_PORT_2=7895
|
||||
# NEKO_BROWSER_PROXY_2=http://172.19.0.1:7895
|
||||
# 留空则自动使用 http://host.docker.internal:${NEKO_SHELLCRASH_PROXY_PORT}
|
||||
# NEKO_BROWSER_PROXY=
|
||||
NETWORK_PROBE_GOOGLE_URL=https://www.google.com/generate_204
|
||||
@ -158,14 +136,12 @@ NEKO_MANAGED_POLICIES=1
|
||||
NEKO_TAMPERMONKEY_REPAIR=1
|
||||
# YouTube Studio 页面实时采集 Chrome 扩展:抓取在线人数、直播状态、健康提示、弹窗内容并写入控制台事件库。
|
||||
NEKO_LIVE_OPS_EXTENSION=1
|
||||
# ICE UDP 段默认避开 52099:ShellCrash CrashCore 常占用该口,否则 live-neko-1 会 bind 失败。
|
||||
# 部署时 render_neko_compose.py 仍会探测外国进程并自动收缩/平移端口。
|
||||
NEKO_WEBRTC_EPR=52000-52098
|
||||
NEKO_WEBRTC_EPR_1=52000-52098
|
||||
NEKO_WEBRTC_EPR=52000-52099
|
||||
NEKO_WEBRTC_EPR_1=52000-52099
|
||||
NEKO_WEBRTC_EPR_2=52101-52199
|
||||
NEKO_WEBRTC_EPR_3=52201-52299
|
||||
NEKO_WEBRTC_UDP_RANGE=52000-52098
|
||||
NEKO_WEBRTC_UDP_RANGE_1=52000-52098
|
||||
NEKO_WEBRTC_UDP_RANGE=52000-52099
|
||||
NEKO_WEBRTC_UDP_RANGE_1=52000-52099
|
||||
NEKO_WEBRTC_UDP_RANGE_2=52101-52199
|
||||
NEKO_WEBRTC_UDP_RANGE_3=52201-52299
|
||||
NEKO_WEBRTC_ICELITE=0
|
||||
@ -187,8 +163,7 @@ NEKO_IP_WATCH_INTERVAL=15
|
||||
NEKO_PLUGINS_ENABLED=true
|
||||
|
||||
# Redroid Android 13(需要 binderfs 或 /dev/binder*;安装脚本会在支持的内核上自动准备)
|
||||
# 默认关闭以节省推流 CPU;控制台可手动 Start
|
||||
ENABLE_REDROID=0
|
||||
ENABLE_REDROID=1
|
||||
REDROID_DEFAULT_PORT=5555
|
||||
REDROID_PORT_STEP=1
|
||||
REDROID_INSTANCE_PREFIX=redroid13
|
||||
@ -222,30 +197,30 @@ ANDROID_PANEL_VIDEO_BIT_RATE=1024000
|
||||
DOCKER_OPTIONAL_INSTALL_TIMEOUT=900
|
||||
# Shared
|
||||
ENABLE_SHELLCRASH=1
|
||||
ENABLE_WEBTTY=0
|
||||
ENABLE_WEBTTY=1
|
||||
ENABLE_BROWSER=1
|
||||
ENABLE_MDNS=1
|
||||
ENABLE_WIFI_PROFILE=1
|
||||
ENABLE_ANDROID_PANEL=0
|
||||
# Hub profile defaults(推流机默认关闭非必要模块,控制台可手动 Start)
|
||||
ENABLE_ANDROID_PANEL=1
|
||||
# Hub profile defaults
|
||||
ENABLE_COCKPIT=1
|
||||
ENABLE_FILEBROWSER=0
|
||||
ENABLE_HOMEPAGE=0
|
||||
ENABLE_FILEBROWSER=1
|
||||
ENABLE_HOMEPAGE=1
|
||||
ENABLE_NETDATA=1
|
||||
ENABLE_MITMPROXY=0
|
||||
ENABLE_MITMPROXY=1
|
||||
MITMPROXY_WEB_PORT=8086
|
||||
MITMPROXY_PROXY_PORT=8087
|
||||
ENABLE_VSCODE_SERVER=0
|
||||
ENABLE_VSCODE_SERVER=1
|
||||
VSCODE_SERVER_PORT=8440
|
||||
VSCODE_SERVER_PASSWORD=12345678
|
||||
ENABLE_UPTIME_KUMA=0
|
||||
ENABLE_UPTIME_KUMA=1
|
||||
UPTIME_KUMA_PORT=3001
|
||||
ENABLE_PULSEAUDIO=0
|
||||
ENABLE_PULSEAUDIO=1
|
||||
PULSEAUDIO_TCP_PORT=4713
|
||||
ENABLE_KMSCUBE=1
|
||||
KMSCUBE_AUTOSTART=0
|
||||
KMSCUBE_DRM_DEVICE=/dev/dri/card0
|
||||
ENABLE_OPENCLAW=0
|
||||
ENABLE_OPENCLAW=1
|
||||
OPENCLAW_IMAGE=ghcr.io/openclaw/openclaw:latest
|
||||
OPENCLAW_GATEWAY_PORT=18789
|
||||
OPENCLAW_BRIDGE_PORT=18790
|
||||
@ -254,14 +229,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(默认关闭,控制台可手动 Start)
|
||||
ENABLE_HOMEASSISTANT=0
|
||||
HOMEASSISTANT_AUTOSTART=0
|
||||
# Studio modules
|
||||
ENABLE_HOMEASSISTANT=1
|
||||
HOMEASSISTANT_AUTOSTART=1
|
||||
HOMEASSISTANT_IMAGE=ghcr.io/home-assistant/home-assistant:stable
|
||||
HOMEASSISTANT_PORT=8123
|
||||
HOMEASSISTANT_CONFIG_DIR=/var/lib/live-homeassistant/config
|
||||
ENABLE_FRIGATE=0
|
||||
FRIGATE_USB_AUTOSTART=0
|
||||
ENABLE_FRIGATE=1
|
||||
FRIGATE_USB_AUTOSTART=1
|
||||
FRIGATE_USB_SCAN_INTERVAL=60
|
||||
FRIGATE_IMAGE=ghcr.io/blakeblackshear/frigate:stable
|
||||
FRIGATE_WEB_PORT=5001
|
||||
@ -276,7 +251,7 @@ WOL_BROADCAST=255.255.255.255
|
||||
WOL_PORT=9
|
||||
WOL_PROBE_INTERVAL=30
|
||||
WOL_PROBE_CIDR=
|
||||
ENABLE_NTFY=0
|
||||
ENABLE_NTFY=1
|
||||
NTFY_IMAGE=binwiederhier/ntfy:latest
|
||||
NTFY_PORT=8089
|
||||
NTFY_CONFIG_DIR=/var/lib/live-ntfy/config
|
||||
@ -289,5 +264,5 @@ COTURN_MIN_PORT=49160
|
||||
COTURN_MAX_PORT=49200
|
||||
COTURN_REALM=live.local
|
||||
COTURN_STATIC_AUTH_SECRET=
|
||||
# Business profile defaults(推流不依赖 SRS,默认关闭)
|
||||
ENABLE_SRS=0
|
||||
# Business profile defaults
|
||||
ENABLE_SRS=1
|
||||
|
||||
@ -8,7 +8,7 @@
|
||||
- 统一入口:`live.local` 由 Caddy `live-edge.service` 承接,默认反代到 `live-console.service`,并由 `live-edge-watch.service` 持续自愈,控制台无需记端口。
|
||||
- 总览:展示硬件、软件、网络、直播业务状态,并给出健康检查、失败原因与下一步操作。
|
||||
- 服务:展示 ShellCrash、SRS、Neko、Redroid、ADB、File Browser、Netdata、WebTTY 等服务的安装、运行、端口与控制按钮。
|
||||
- YouTube 无人直播:控制台**默认多频道 Pro**(单频道逻辑保留、UI 切换隐藏)。每条 Pro 线路独立保存 URL、推流密钥、PM2 进程、日志、Neko 工作室入口。
|
||||
- YouTube 无人直播:单频道与多频道 Pro 共存。每条 Pro 线路独立保存 URL、推流密钥、PM2 进程、日志、Neko 工作室入口。
|
||||
- TikTok 无人直播:视频源转发到设备 HDMI,面板可检测输出设备、预览命令、启动/停止链路。
|
||||
- 安卓:Redroid 与真实手机都通过 ADB 识别;Web 面板可看屏、点按、长按、输入、安装 APK、批量执行命令。
|
||||
- 网络:ShellCrash 解决单机代理上网,面板展示实时/累计上行下行、代理状态、DNS 与出口连通性。
|
||||
|
||||
@ -1,82 +0,0 @@
|
||||
# Deploy hardening notes (x86 / ARM)
|
||||
|
||||
Lessons from production deploys on Ubuntu (x86_64 and aarch64) behind Soft Router / WireGuard.
|
||||
|
||||
## Architecture
|
||||
|
||||
Install scripts detect CPU once and reuse labels:
|
||||
|
||||
| `uname -m` | ShellCrash `cpucore` | Docker Compose asset |
|
||||
|------------|----------------------|----------------------|
|
||||
| `x86_64` / `amd64` | `amd64` | `x86_64` |
|
||||
| `aarch64` / `arm64` | `arm64` | `aarch64` |
|
||||
| `armv7*` / `armhf` | `armv7` | `armv7` |
|
||||
|
||||
`harden_shellcrash_runtime` refreshes `cpucore` on every install so a copied image cannot keep the wrong binary label.
|
||||
|
||||
## ShellCrash dashboard blocked on WireGuard
|
||||
|
||||
Symptom: ShellCrash shows online and has YAML, but `http://10.66.66.x:9999/ui/` (or `10.88.0.x`) fails from WG peers while localhost works — or browser shows `ERR_CONNECTION_REFUSED`.
|
||||
|
||||
Causes:
|
||||
|
||||
1. ShellCrash nftables WAN firewall accepts only physical LAN (`HOST_IP`) then **rejects** `7890` / `9999`. WireGuard overlays are not in that accept set.
|
||||
2. CrashCore never binds `:9999` because profile validation fails:
|
||||
- removed top-level `global-client-fingerprint` (new mihomo/meta)
|
||||
- missing `Country.mmdb` / GeoIP when GitHub downloads time out
|
||||
|
||||
Fix in tree:
|
||||
|
||||
- `SHELLCRASH_WG_CIDR` / `SHELLCRASH_TRUSTED_CIDRS` (see `config/system-stack.env.example`; defaults include both `10.66.66.0/24` and `10.88.0.0/24`)
|
||||
- `ensure_shellcrash_proxy_ports_for_docker` also opens dashboard `db_port`
|
||||
- systemd drop-in `shellcrash.service.d/allow-trusted.conf` + `/usr/local/sbin/shellcrash-allow-trusted.sh` re-applies after every ShellCrash start
|
||||
- `shellcrash_patch_runtime_yaml` strips `global-client-fingerprint` and forces `external-controller: 0.0.0.0:9999`
|
||||
- `ensure_shellcrash_geo_databases` pulls GeoSite/GeoIP/MMDB via jsdelivr when GitHub is unreachable
|
||||
- `shellcrash.service.d/timeout.conf` raises `TimeoutStartSec=600` (bfstart + geo load exceeds 90s)
|
||||
|
||||
## Install-time proxy
|
||||
|
||||
When the host cannot reach Docker Hub / GitHub / PyPI / Ubuntu archives directly (typical behind GFW with a LAN Clash on Windows):
|
||||
|
||||
```bash
|
||||
export LIVE_HTTP_PROXY=http://192.168.21.36:7897
|
||||
export LIVE_HTTPS_PROXY="$LIVE_HTTP_PROXY"
|
||||
export LIVE_NO_PROXY=localhost,127.0.0.1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,*.lan,*.local
|
||||
sudo -E bash ./install.sh --local-only --profile all
|
||||
# optional: clear LIVE_* afterwards so runtime stays direct
|
||||
```
|
||||
|
||||
What the installer does when `LIVE_HTTP_PROXY` is set:
|
||||
|
||||
1. Exports shell `http(s)_proxy` for curl / apt / pip / git helpers.
|
||||
2. Writes `/etc/apt/apt.conf.d/99live-proxy` so `apt-get` keeps working in child processes.
|
||||
3. Writes `/etc/systemd/system/docker.service.d/http-proxy.conf` and reloads Docker **before** Neko/image pulls (daemon does not inherit shell proxy).
|
||||
4. On Neko `compose up` timeout, re-applies the Docker proxy drop-in and retries once.
|
||||
|
||||
Installer downloads for ShellCrash also try with proxy and without (`--noproxy` / unset env).
|
||||
|
||||
## WireGuard + Neko
|
||||
|
||||
- Overlay address for this fleet is typically `10.66.66.0/24` (腾讯云) or legacy `10.88.0.0/24`.
|
||||
- **`sync_neko_wireguard_remote_access`** (in `scripts/linux/lib/common.sh` and `service_ctl.sh`): when a `wg*` / `wgeasy` interface is up, the installer and `service_ctl neko` persist `NEKO_ACCESS_MODE=remote`, `NEKO_WIREGUARD_HOST`, and `NEKO_WEBRTC_NAT1TO1` into `config/system-stack.env` so restarts do not drift back to the physical LAN IP.
|
||||
- **`ensure_neko_webrtc_ports_for_trusted_cidrs`**: opens ShellCrash trusted accept rules for overlay CIDRs so Neko HTTP `:920x` and WebRTC UDP/TCP mux ports work over WireGuard, not only on the physical LAN.
|
||||
- **`live-wireguard-watch.service`**: after restarting a stale `wg-quick@*.service`, calls Neko reconfigure so WebRTC candidates stay aligned with the overlay IP.
|
||||
- `resolve_neko_nat1to1` auto-picks `wg*` / overlay `10.x` when remote mode is set.
|
||||
- Applying a WG conf via the hub also switches Neko to remote when the overlay address is ready, and re-runs the ShellCrash trusted-CIDR hook.
|
||||
|
||||
## Neko browser proxy (ShellCrash)
|
||||
|
||||
- Default: `ENABLE_NEKO_BROWSER_PROXY=0` → Neko uses ShellCrash mixed port **7890** when direct Google/YouTube fails.
|
||||
- Optional proxycheap listener **7894** is enabled only when egress probe through that port succeeds (`shellcrash_proxy_egress_ready` / `shellcrash_listener_egress_ok`); a listening but dead upstream no longer auto-flips the switch on fresh installs.
|
||||
|
||||
## Ports to remember
|
||||
|
||||
| Service | Default |
|
||||
|---------|---------|
|
||||
| Control plane | `8001` |
|
||||
| Caddy edge | `80` → `8001` |
|
||||
| Homepage | `3080` (not `80`) |
|
||||
| ShellCrash UI | `9999` |
|
||||
| ShellCrash mixed | `7890` |
|
||||
| WebTTY | `7681` |
|
||||
| File Browser | `8082` |
|
||||
@ -102,12 +102,10 @@ That means the TCP connection was **rejected or nothing listens** on the address
|
||||
4. From a **laptop/phone**, open **`http://<device-LAN-IP>:8001/`** first (same Wi‑Fi). If that works but `http://live.local` does not, the problem is **mDNS** (Windows often needs Bonjour) or you’re not on the same LAN — use the IP bookmark.
|
||||
5. **Firewall** (nftables/ufw) blocking **80/8001** from Wi‑Fi will also show as “refused” from other hosts while loopback still works.
|
||||
|
||||
### PM2:多频道 Pro(Linux ARM / x86_64,控制台默认)
|
||||
### PM2:单频道与多频道 Pro(Linux ARM / x86_64)
|
||||
|
||||
Web 控制台 **YouTube 无人直播** 默认进入多频道 Pro;每条线路在 SQLite 落盘并生成独立配置文件。
|
||||
|
||||
- **多频道 Pro(默认)**:每路直播需要**独立的** `config/youtube.<pm2>.ini` 与 `config/URL_config.<pm2>.ini`。控制台保存线路时自动创建;PM2 名与 Web 线路一致(如 `youtube2__<channelId>`)。
|
||||
- **单频道(遗留)**:仍可通过 PM2 手动启一个 `youtube` / `tiktok` 进程;控制台 UI 切换已隐藏,见 `LiveYoutubeUnmannedView.tsx` 中 `HIDE_YOUTUBE_MODE_TOGGLE`。
|
||||
- **单频道**:在项目根启用一个业务进程即可,例如取消注释 `ecosystem.config.cjs` 里的 `youtube` 或 `tiktok`,执行 `pm2 start ecosystem.config.cjs && pm2 save`。
|
||||
- **多频道 Pro**:每路直播需要**独立的** `config/youtube.ini` 与 `config/URL_config.ini`(或整份独立工作目录)。为第二路及以后各复制一份目录(或符号链接脚本外的配置),在 PM2 里为每个 app 设置不同的 `cwd`,`name` 与 Web 控制台 Pro 线路建议名一致(如 `youtube2__<channelId>`)。
|
||||
- **硬件编码**:`sudo python3 scripts/hardware_probe.py --write` 会写入 `config/hardware.env` 与 `hardware-profile.json`;推流侧可选 `LIVE_VIDEO_ENCODER`(RKMPP / V4L2M2M / VA-API / QSV 等,见 `config/hardware.env.example`)。NVIDIA 一般由 `douyin_youtube_ffplay.py` 自动走 NVENC。
|
||||
- **音频链**:与 GitLab 分支 `ffmpegAudioRMFoode` 中 `douyin_youtube_ffplay.py` 的 FFmpeg 处理思路一致(`fast_audio`、arnndn、EQ 等);当前主线在 Linux 上还包含板载编码探测与推流稳定性增强,以前端无需对齐 Electron 为准。
|
||||
|
||||
|
||||
@ -18,12 +18,6 @@
|
||||
- wandaB:`wgeasy` 使用 `Endpoint = 129.204.21.129:51820`,`Address = 10.88.0.2/32`;到 `10.88.0.1` 的延迟约 25ms。
|
||||
- Neko 访问优先级:WireGuard `10.88.0.0/24` 优先,frp 公网端口兜底,EasyTier `10.126.126.0/24` 作为备用运维链路。
|
||||
|
||||
## ShellCrash dashboard over WireGuard
|
||||
|
||||
ShellCrash `firewall_area=1` rejects WAN access to `7890` / `9999` after accepting only the physical LAN. WireGuard peers (`10.88.0.0/24`) must be added to the trusted accept set or the UI shows “online” locally but `http://10.88.0.x:9999/ui/` fails from remote.
|
||||
|
||||
See `docs/deploy-hardening.md` for `SHELLCRASH_TRUSTED_CIDRS` / `shellcrash-allow-trusted.sh`.
|
||||
|
||||
## 推荐参数
|
||||
|
||||
WireGuard peer 推荐:
|
||||
|
||||
@ -436,17 +436,6 @@ 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
|
||||
@ -773,23 +762,6 @@ 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"))
|
||||
@ -1009,13 +981,9 @@ def start_douyin_youtube_ffplay(
|
||||
_seen_source: set[str] = set()
|
||||
for item in [real_url, *(fallback_urls or [])]:
|
||||
u = (item or "").strip()
|
||||
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 u and u not in _seen_source:
|
||||
_seen_source.add(u)
|
||||
source_candidates.append(u)
|
||||
if not source_candidates:
|
||||
source_candidates = [real_url]
|
||||
source_index = 0
|
||||
@ -1277,12 +1245,6 @@ 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)
|
||||
|
||||
@ -65,7 +65,6 @@ Options:
|
||||
|
||||
Environment overrides:
|
||||
LIVE_REPO_URL, LIVE_REPO_REF, LIVE_REPO_SUBDIR, LIVE_INSTALL_DIR
|
||||
LIVE_HTTP_PROXY, LIVE_HTTPS_PROXY, LIVE_NO_PROXY (install-time apt/Docker proxy)
|
||||
HOSTNAME_ALIAS, PORT and other config/system-stack.env values
|
||||
USAGE
|
||||
}
|
||||
@ -345,15 +344,6 @@ install_profile() {
|
||||
LIVE_STACK_REPO_ROOT="$INSTALL_DIR" \
|
||||
LIVE_INSTALL_LOG_FILE="$LOG_FILE" \
|
||||
ASSUME_YES="$ASSUME_YES" \
|
||||
LIVE_HTTP_PROXY="${LIVE_HTTP_PROXY:-}" \
|
||||
LIVE_HTTPS_PROXY="${LIVE_HTTPS_PROXY:-}" \
|
||||
LIVE_NO_PROXY="${LIVE_NO_PROXY:-}" \
|
||||
http_proxy="${http_proxy:-${LIVE_HTTP_PROXY:-}}" \
|
||||
https_proxy="${https_proxy:-${LIVE_HTTPS_PROXY:-${LIVE_HTTP_PROXY:-}}}" \
|
||||
HTTP_PROXY="${HTTP_PROXY:-${LIVE_HTTP_PROXY:-}}" \
|
||||
HTTPS_PROXY="${HTTPS_PROXY:-${LIVE_HTTPS_PROXY:-${LIVE_HTTP_PROXY:-}}}" \
|
||||
no_proxy="${no_proxy:-${LIVE_NO_PROXY:-}}" \
|
||||
NO_PROXY="${NO_PROXY:-${LIVE_NO_PROXY:-}}" \
|
||||
bash "$stack" "$PROFILE"
|
||||
}
|
||||
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "android_panel",
|
||||
"layer": "infra",
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"manager": "systemd",
|
||||
"ports": { "http": 5000 },
|
||||
"env": {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "filebrowser",
|
||||
"layer": "infra",
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"manager": "docker",
|
||||
"ports": { "http": 8082 },
|
||||
"env": {
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
{
|
||||
"id": "frigate",
|
||||
"layer": "studio",
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"manager": "docker",
|
||||
"ports": { "http": 5001, "rtsp": 8554, "webrtc": 8555 },
|
||||
"env": {
|
||||
"ENABLE_FRIGATE": "0",
|
||||
"ENABLE_FRIGATE": "1",
|
||||
"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": false,
|
||||
"enabled": true,
|
||||
"manager": "docker",
|
||||
"ports": { "http": 8123 },
|
||||
"env": {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "homepage",
|
||||
"layer": "infra",
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"manager": "docker",
|
||||
"ports": { "http": 3080 },
|
||||
"env": { "ENABLE_HOMEPAGE": "1", "HOMEPAGE_PORT": "3080" }
|
||||
|
||||
@ -17,8 +17,8 @@
|
||||
"NEKO_MAX_FPS": "15",
|
||||
"NEKO_VIDEO_BITRATE": "1200",
|
||||
"NEKO_BROWSER_RENDER_MODE": "auto",
|
||||
"NEKO_WEBRTC_UDP_RANGE": "52000-52098",
|
||||
"NEKO_WEBRTC_UDP_RANGE_1": "52000-52098",
|
||||
"NEKO_WEBRTC_UDP_RANGE": "52000-52099",
|
||||
"NEKO_WEBRTC_UDP_RANGE_1": "52000-52099",
|
||||
"NEKO_WEBRTC_UDP_RANGE_2": "52101-52199",
|
||||
"NEKO_WEBRTC_UDP_RANGE_3": "52201-52299",
|
||||
"NEKO_WEBRTC_TCPMUX": "52300",
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "ntfy",
|
||||
"layer": "studio",
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"manager": "docker",
|
||||
"ports": { "http": 8089 },
|
||||
"env": {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "srs",
|
||||
"layer": "infra",
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"manager": "docker",
|
||||
"ports": {
|
||||
"http": 8080,
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "webtty",
|
||||
"layer": "core",
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"manager": "systemd",
|
||||
"ports": { "http": 7681 },
|
||||
"env": {
|
||||
|
||||
@ -460,13 +460,6 @@ 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
|
||||
@ -1183,25 +1176,11 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
|
||||
else:
|
||||
content = f"\r{record_name} 正在直播中..."
|
||||
print(content)
|
||||
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 len(recording) > 0 :
|
||||
# 如果已有直播在录制,跳过这次录制(主播在线)
|
||||
# return
|
||||
continue #如果在循环中
|
||||
|
||||
if live_status_push and not start_pushed:
|
||||
if begin_show_push:
|
||||
|
||||
@ -39,21 +39,3 @@
|
||||
4. 部署注意
|
||||
- `live.local` 实际运行目录不是当前仓库 `/home/eric/sh/d2ypp2`,而是 `/home/eric/d2ypp`。
|
||||
- 如果只改当前目录而不把修复同步到 `/home/eric/d2ypp`,`live.local` 不会生效。
|
||||
|
||||
---
|
||||
|
||||
项目修复记录(2026-08-26)
|
||||
|
||||
1. 一键安装 / Neko / WireGuard
|
||||
- WireGuard overlay 上线后,`install_neko_browser` 与 `service_ctl neko` 通过 `sync_neko_wireguard_remote_access` 自动写入 `NEKO_ACCESS_MODE=remote`、`NEKO_WIREGUARD_HOST`、`NEKO_WEBRTC_NAT1TO1`,避免 WebRTC 仍广播物理网 IP 导致黑屏/重连。
|
||||
- `ensure_neko_webrtc_ports_for_trusted_cidrs` 在 ShellCrash WAN 防火墙下为 overlay 网段放行 Neko HTTP/WebRTC;`wireguard_watch` 在 WG 重启后自动 reconfigure Neko。
|
||||
- Neko 浏览器代理:`shellcrash_proxy_egress_ready` 实测 Google 204 后再选端口;proxycheap `:7894` 不可用时保持 `ENABLE_NEKO_BROWSER_PROXY=0`,走 mixed `:7890`。
|
||||
|
||||
2. YouTube 无人直播控制台
|
||||
- 默认多频道 Pro,隐藏「单频道 / 多频道」切换条(`HIDE_YOUTUBE_MODE_TOGGLE`)。
|
||||
|
||||
3. 关键文件
|
||||
- `scripts/linux/lib/common.sh`、`scripts/linux/service_ctl.sh`、`scripts/linux/wireguard_watch.sh`
|
||||
- `src/network_preflight.py`、`src/wireguard_config.py`
|
||||
- `web-console/components/live-product/LiveYoutubeUnmannedView.tsx`
|
||||
- `docs/deploy-hardening.md`、`README.md`
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -8,7 +8,6 @@ INSTALL_TAG="${INSTALL_TAG:-neko-ip-watch}"
|
||||
reload_watch_env() {
|
||||
unset ENABLE_NEKO NEKO_ACCESS_MODE NEKO_WEBRTC_NAT1TO1 NEKO_IP_WATCH_INTERVAL
|
||||
if [ -f "$STACK_ENV" ]; then
|
||||
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||
set -a
|
||||
. "$STACK_ENV"
|
||||
set +a
|
||||
@ -54,7 +53,13 @@ maybe_refresh_neko_for_ip_change() {
|
||||
return 0
|
||||
fi
|
||||
|
||||
target="$(resolve_neko_nat1to1 || true)"
|
||||
preferred="$(detect_preferred_lan_ip || true)"
|
||||
target="$preferred"
|
||||
case "${NEKO_ACCESS_MODE:-lan}" in
|
||||
remote)
|
||||
target="${NEKO_WEBRTC_NAT1TO1:-}"
|
||||
;;
|
||||
esac
|
||||
if [ -z "$target" ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
@ -26,20 +26,13 @@ COTURN_COMPOSE="$ROOT_DIR/services/coturn/docker-compose.yml"
|
||||
BROWSER_LAUNCHER="$ROOT_DIR/scripts/linux/launch_browser.sh"
|
||||
KMSCUBE_LAUNCHER="$ROOT_DIR/scripts/linux/run_kmscube.sh"
|
||||
|
||||
# SFTP/Windows editors often leave CR; sourcing then breaks ports as "9200\r".
|
||||
if [ -f "$STACK_ENV" ]; then
|
||||
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||
set -a && . "$STACK_ENV" && set +a
|
||||
fi
|
||||
if [ -f "$HW_ENV" ]; then
|
||||
sed -i 's/\r$//' "$HW_ENV" 2>/dev/null || true
|
||||
set -a && . "$HW_ENV" && set +a
|
||||
fi
|
||||
[ -f "$STACK_ENV" ] && set -a && . "$STACK_ENV" && set +a
|
||||
[ -f "$HW_ENV" ] && set -a && . "$HW_ENV" && set +a
|
||||
|
||||
HOSTNAME_ALIAS="${HOSTNAME_ALIAS:-live}"
|
||||
PORT="${PORT:-8001}"
|
||||
WEBTTY_PORT="${WEBTTY_PORT:-7681}"
|
||||
HOMEPAGE_PORT="${HOMEPAGE_PORT:-3080}"
|
||||
HOMEPAGE_PORT="${HOMEPAGE_PORT:-80}"
|
||||
FILEBROWSER_PORT="${FILEBROWSER_PORT:-8082}"
|
||||
NETDATA_PORT="${NETDATA_PORT:-19999}"
|
||||
SRS_HTTP_PORT="${SRS_HTTP_PORT:-8080}"
|
||||
@ -56,8 +49,6 @@ SHELLCRASH_ATTACH_WHEN_DIRECT_OK="${SHELLCRASH_ATTACH_WHEN_DIRECT_OK:-0}"
|
||||
SHELLCRASH_ATTACH_NEKO="${SHELLCRASH_ATTACH_NEKO:-auto}"
|
||||
SHELLCRASH_ATTACH_FFMPEG="${SHELLCRASH_ATTACH_FFMPEG:-auto}"
|
||||
SHELLCRASH_DOCKER_CIDR="${SHELLCRASH_DOCKER_CIDR:-172.16.0.0/12}"
|
||||
SHELLCRASH_WG_CIDR="${SHELLCRASH_WG_CIDR:-10.88.0.0/24}"
|
||||
SHELLCRASH_TRUSTED_CIDRS="${SHELLCRASH_TRUSTED_CIDRS:-}"
|
||||
ENABLE_NEKO_BROWSER_PROXY="${ENABLE_NEKO_BROWSER_PROXY:-0}"
|
||||
NEKO_SHELLCRASH_PROXY_PORT="${NEKO_SHELLCRASH_PROXY_PORT:-7894}"
|
||||
SHELLCRASH_NEKO_PROXY_NODE="${SHELLCRASH_NEKO_PROXY_NODE:-proxycheap}"
|
||||
@ -93,8 +84,7 @@ NEKO_WEBRTC_TCPMUX_3="${NEKO_WEBRTC_TCPMUX_3:-52302}"
|
||||
NEKO_WEBRTC_UDPMUX_1="${NEKO_WEBRTC_UDPMUX_1:-$NEKO_WEBRTC_UDPMUX}"
|
||||
NEKO_WEBRTC_UDPMUX_2="${NEKO_WEBRTC_UDPMUX_2:-52301}"
|
||||
NEKO_WEBRTC_UDPMUX_3="${NEKO_WEBRTC_UDPMUX_3:-52302}"
|
||||
# Default ends at .98: ShellCrash CrashCore has been observed binding UDP 52099.
|
||||
NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52098}"
|
||||
NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52099}"
|
||||
NEKO_WEBRTC_UDP_RANGE_1="${NEKO_WEBRTC_UDP_RANGE_1:-$NEKO_WEBRTC_UDP_RANGE}"
|
||||
NEKO_WEBRTC_UDP_RANGE_2="${NEKO_WEBRTC_UDP_RANGE_2:-52101-52199}"
|
||||
NEKO_WEBRTC_UDP_RANGE_3="${NEKO_WEBRTC_UDP_RANGE_3:-52201-52299}"
|
||||
@ -119,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:-0}"
|
||||
ENABLE_MITMPROXY="${ENABLE_MITMPROXY:-1}"
|
||||
MITMPROXY_WEB_PORT="${MITMPROXY_WEB_PORT:-8086}"
|
||||
MITMPROXY_PROXY_PORT="${MITMPROXY_PROXY_PORT:-8087}"
|
||||
ENABLE_VSCODE_SERVER="${ENABLE_VSCODE_SERVER:-0}"
|
||||
ENABLE_VSCODE_SERVER="${ENABLE_VSCODE_SERVER:-1}"
|
||||
VSCODE_SERVER_PORT="${VSCODE_SERVER_PORT:-8440}"
|
||||
VSCODE_SERVER_PASSWORD="${VSCODE_SERVER_PASSWORD:-12345678}"
|
||||
ENABLE_UPTIME_KUMA="${ENABLE_UPTIME_KUMA:-0}"
|
||||
ENABLE_UPTIME_KUMA="${ENABLE_UPTIME_KUMA:-1}"
|
||||
UPTIME_KUMA_PORT="${UPTIME_KUMA_PORT:-3001}"
|
||||
ENABLE_PULSEAUDIO="${ENABLE_PULSEAUDIO:-0}"
|
||||
ENABLE_PULSEAUDIO="${ENABLE_PULSEAUDIO:-1}"
|
||||
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:-0}"
|
||||
ENABLE_OPENCLAW="${ENABLE_OPENCLAW:-1}"
|
||||
OPENCLAW_IMAGE="${OPENCLAW_IMAGE:-ghcr.io/openclaw/openclaw:latest}"
|
||||
OPENCLAW_GATEWAY_PORT="${OPENCLAW_GATEWAY_PORT:-18789}"
|
||||
OPENCLAW_BRIDGE_PORT="${OPENCLAW_BRIDGE_PORT:-18790}"
|
||||
@ -139,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:-0}"
|
||||
HOMEASSISTANT_AUTOSTART="${HOMEASSISTANT_AUTOSTART:-0}"
|
||||
ENABLE_HOMEASSISTANT="${ENABLE_HOMEASSISTANT:-1}"
|
||||
HOMEASSISTANT_AUTOSTART="${HOMEASSISTANT_AUTOSTART:-1}"
|
||||
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:-0}"
|
||||
FRIGATE_USB_AUTOSTART="${FRIGATE_USB_AUTOSTART:-0}"
|
||||
ENABLE_FRIGATE="${ENABLE_FRIGATE:-1}"
|
||||
FRIGATE_USB_AUTOSTART="${FRIGATE_USB_AUTOSTART:-1}"
|
||||
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}"
|
||||
@ -160,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:-0}"
|
||||
ENABLE_NTFY="${ENABLE_NTFY:-1}"
|
||||
NTFY_IMAGE="${NTFY_IMAGE:-binwiederhier/ntfy:latest}"
|
||||
NTFY_PORT="${NTFY_PORT:-8089}"
|
||||
NTFY_CONFIG_DIR="${NTFY_CONFIG_DIR:-/var/lib/live-ntfy/config}"
|
||||
@ -176,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:-0}"
|
||||
ENABLE_REDROID="${ENABLE_REDROID:-1}"
|
||||
REDROID_DEFAULT_PORT="${REDROID_DEFAULT_PORT:-5555}"
|
||||
REDROID_INSTANCE_PREFIX="${REDROID_INSTANCE_PREFIX:-redroid13}"
|
||||
REDROID_DATA_PREFIX="${REDROID_DATA_PREFIX:-/var/lib/live-redroid}"
|
||||
@ -227,29 +217,11 @@ stack_env_upsert() {
|
||||
[ -n "$key" ] || return 1
|
||||
mkdir -p "$(dirname "$STACK_ENV")"
|
||||
touch "$STACK_ENV"
|
||||
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||
value="${value//$'\r'/}"
|
||||
local prefix="${key}=" next_line="${key}=${value}"
|
||||
local line kept="" found=0
|
||||
: >"${STACK_ENV}.tmp"
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
case "$line" in
|
||||
"${prefix}"*)
|
||||
if [ "$found" -eq 0 ]; then
|
||||
printf '%s\n' "$next_line" >>"${STACK_ENV}.tmp"
|
||||
found=1
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
printf '%s\n' "$line" >>"${STACK_ENV}.tmp"
|
||||
;;
|
||||
esac
|
||||
done <"$STACK_ENV"
|
||||
if [ "$found" -eq 0 ]; then
|
||||
printf '%s\n' "$next_line" >>"${STACK_ENV}.tmp"
|
||||
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
|
||||
mv "${STACK_ENV}.tmp" "$STACK_ENV"
|
||||
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||
}
|
||||
|
||||
neko_browser_proxy_auto_enable_if_needed() {
|
||||
@ -261,10 +233,10 @@ neko_browser_proxy_auto_enable_if_needed() {
|
||||
system_direct_global_ready && return 0
|
||||
local port
|
||||
port="$(shellcrash_neko_proxy_port)"
|
||||
if ! shellcrash_proxy_egress_ready "$port"; then
|
||||
if ! shellcrash_proxy_available "$port"; then
|
||||
shellcrash_autostart_if_needed >/dev/null 2>&1 || true
|
||||
port="$(shellcrash_neko_proxy_port)"
|
||||
shellcrash_proxy_egress_ready "$port" || return 0
|
||||
shellcrash_proxy_available "$port" || return 0
|
||||
fi
|
||||
stack_env_upsert ENABLE_NEKO_BROWSER_PROXY 1
|
||||
export ENABLE_NEKO_BROWSER_PROXY=1
|
||||
@ -803,16 +775,7 @@ render_neko_compose_file() {
|
||||
local count out
|
||||
count="$(resolve_neko_instance_count)"
|
||||
out="$ROOT_DIR/services/neko/docker-compose.generated.yml"
|
||||
# Autofix skips CrashCore/foreign UDP holders inside ICE ranges and strips CRLF in stack env.
|
||||
python3 "$ROOT_DIR/tools/render_neko_compose.py" \
|
||||
--count "$count" \
|
||||
--output "$out" \
|
||||
--stack-env "$STACK_ENV"
|
||||
# Reload ranges if renderer persisted changes.
|
||||
if [ -f "$STACK_ENV" ]; then
|
||||
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||
set -a && . "$STACK_ENV" && set +a
|
||||
fi
|
||||
python3 "$ROOT_DIR/tools/render_neko_compose.py" --count "$count" --output "$out"
|
||||
printf '%s' "$out"
|
||||
}
|
||||
|
||||
@ -1007,10 +970,11 @@ hosts.write_text("\\n".join(next_host_lines) + "\\n", encoding="utf-8")
|
||||
PY
|
||||
}
|
||||
|
||||
neko_nat1to1_iface_for_ip() {
|
||||
neko_nat1to1_is_usable() {
|
||||
local candidate="$1"
|
||||
local iface
|
||||
[ -n "$candidate" ] || return 1
|
||||
ip -4 addr show 2>/dev/null | awk -v want="$candidate" '
|
||||
iface="$(ip -4 addr show 2>/dev/null | awk -v want="$candidate" '
|
||||
/^[0-9]+: / {
|
||||
iface=$2
|
||||
sub(/:$/, "", iface)
|
||||
@ -1023,145 +987,7 @@ neko_nat1to1_iface_for_ip() {
|
||||
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
|
||||
}
|
||||
|
||||
detect_wireguard_overlay_ip() {
|
||||
local path name ip preferred="${SHELLCRASH_WG_CIDR:-10.88.0.0/24}"
|
||||
preferred="${preferred%%/*}"
|
||||
preferred="${preferred%.*}"
|
||||
for path in /sys/class/net/*; do
|
||||
[ -e "$path" ] || continue
|
||||
name="${path##*/}"
|
||||
case "$name" in
|
||||
wg*|wgeasy|wireguard*) ;;
|
||||
*) continue ;;
|
||||
esac
|
||||
ip="$(ip -4 addr show dev "$name" 2>/dev/null | awk '$1=="inet" {sub(/\/.*/, "", $2); print $2; exit}')"
|
||||
[ -n "$ip" ] || continue
|
||||
if [ -n "$preferred" ] && printf '%s' "$ip" | grep -q "^${preferred}\\."; then
|
||||
printf '%s\n' "$ip"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
for path in /sys/class/net/*; do
|
||||
[ -e "$path" ] || continue
|
||||
name="${path##*/}"
|
||||
case "$name" in
|
||||
wg*|wgeasy|wireguard*) ;;
|
||||
*) continue ;;
|
||||
esac
|
||||
ip="$(ip -4 addr show dev "$name" 2>/dev/null | awk '$1=="inet" {sub(/\/.*/, "", $2); print $2; exit}')"
|
||||
if [ -n "$ip" ]; then
|
||||
printf '%s\n' "$ip"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
sync_neko_wireguard_remote_access() {
|
||||
local wg_ip="" target="" persist="${1:-1}"
|
||||
wg_ip="$(detect_wireguard_overlay_ip || true)"
|
||||
[ -n "$wg_ip" ] || return 1
|
||||
case "${NEKO_ACCESS_MODE:-lan}" in
|
||||
lan|remote)
|
||||
export NEKO_ACCESS_MODE=remote
|
||||
export NEKO_WIREGUARD_HOST="${NEKO_WIREGUARD_HOST:-$wg_ip}"
|
||||
;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
target="$(resolve_neko_nat1to1 || true)"
|
||||
[ -n "$target" ] || return 1
|
||||
export NEKO_WEBRTC_NAT1TO1="$target"
|
||||
if [ "$persist" = "1" ]; then
|
||||
stack_env_upsert NEKO_ACCESS_MODE remote
|
||||
stack_env_upsert NEKO_WIREGUARD_HOST "$wg_ip"
|
||||
stack_env_upsert NEKO_WEBRTC_NAT1TO1 "$target"
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
ensure_neko_webrtc_ports_for_trusted_cidrs() {
|
||||
local cidr
|
||||
[ "${ENABLE_NEKO:-1}" = "1" ] || return 0
|
||||
while IFS= read -r cidr; do
|
||||
[ -n "$cidr" ] || continue
|
||||
ensure_shellcrash_docker_port_access "9200" tcp "Neko/WebRTC from trusted overlay"
|
||||
done <<EOF
|
||||
$(shellcrash_trusted_cidrs)
|
||||
EOF
|
||||
[ -x /usr/local/sbin/shellcrash-allow-trusted.sh ] && /usr/local/sbin/shellcrash-allow-trusted.sh >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
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
|
||||
candidate="$(detect_wireguard_overlay_ip 2>/dev/null || true)"
|
||||
if [ -z "$candidate" ]; then
|
||||
candidate="$(ip -4 addr show 2>/dev/null | awk '
|
||||
/^[0-9]+: / { iface=$2; sub(/:$/, "", iface) }
|
||||
$1=="inet" {
|
||||
ip=$2; sub(/\/.*/, "", ip)
|
||||
if (iface ~ /^(wg|wgeasy|wireguard)/ && ip ~ /^10\.88\.0\./) { print ip; exit }
|
||||
}
|
||||
')"
|
||||
fi
|
||||
if [ -n "$candidate" ] && neko_nat1to1_is_usable "$candidate"; then
|
||||
printf '%s' "$candidate"
|
||||
return 0
|
||||
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
|
||||
@ -1509,18 +1335,19 @@ neko_browser_proxy_url_is_usable() {
|
||||
host.docker.internal)
|
||||
return 0
|
||||
;;
|
||||
10.*|192.168.*|172.1[6-9].*|172.2[0-9].*|172.3[0-1].*)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
neko_docker_bridge_ipv4_is_usable "$host"
|
||||
}
|
||||
|
||||
neko_proxy_url_for_port() {
|
||||
local port="$1"
|
||||
local port="$1" host_ip
|
||||
[ -n "$port" ] || return 1
|
||||
# Use host.docker.internal; compose extra_hosts maps it to the reachable host gateway.
|
||||
printf 'http://host.docker.internal:%s' "$port"
|
||||
host_ip="$(resolve_neko_docker_host_ip)"
|
||||
if [ "$host_ip" = "host-gateway" ] || ! neko_docker_bridge_ipv4_is_usable "$host_ip"; then
|
||||
printf 'http://host.docker.internal:%s' "$port"
|
||||
else
|
||||
printf 'http://%s:%s' "$host_ip" "$port"
|
||||
fi
|
||||
}
|
||||
|
||||
shellcrash_docker_cidr() {
|
||||
@ -1531,25 +1358,9 @@ shellcrash_docker_cidr() {
|
||||
printf '%s' "$cidr"
|
||||
}
|
||||
|
||||
shellcrash_trusted_cidrs() {
|
||||
local raw item
|
||||
if [ -n "${SHELLCRASH_TRUSTED_CIDRS:-}" ]; then
|
||||
raw="$SHELLCRASH_TRUSTED_CIDRS"
|
||||
else
|
||||
raw="$(shellcrash_docker_cidr),${SHELLCRASH_WG_CIDR:-10.88.0.0/24},10.66.66.0/24,10.88.0.0/24,192.168.0.0/16,10.0.0.0/8"
|
||||
fi
|
||||
raw="$(printf '%s' "$raw" | tr ',;' ' ')"
|
||||
for item in $raw; do
|
||||
case "$item" in
|
||||
''|*[!0-9./]*) continue ;;
|
||||
*) printf '%s\n' "$item" ;;
|
||||
esac
|
||||
done | awk 'NF && !seen[$0]++'
|
||||
}
|
||||
|
||||
ensure_ufw_shellcrash_docker_access() {
|
||||
local port="$1" proto="$2" comment="$3" cidr="$4"
|
||||
cidr="${cidr:-$(shellcrash_docker_cidr)}"
|
||||
local port="$1" proto="$2" comment="$3" cidr
|
||||
cidr="$(shellcrash_docker_cidr)"
|
||||
have ufw || return 1
|
||||
ufw status 2>/dev/null | grep -q '^Status: active' || return 1
|
||||
ufw_shellcrash_docker_rule_exists "$port" "$proto" "$cidr" && return 0
|
||||
@ -1575,26 +1386,21 @@ ensure_shellcrash_docker_port_access() {
|
||||
tcp|udp) ;;
|
||||
*) return 0 ;;
|
||||
esac
|
||||
while IFS= read -r cidr; do
|
||||
[ -n "$cidr" ] || continue
|
||||
ufw_rule_ok=0
|
||||
if ensure_ufw_shellcrash_docker_access "$port" "$proto" "$comment" "$cidr"; then
|
||||
ufw_rule_ok=1
|
||||
fi
|
||||
if have nft && nft list chain inet shellcrash input >/dev/null 2>&1; then
|
||||
if ! nft list chain inet shellcrash input 2>/dev/null | grep -Fq "ip saddr $cidr accept"; then
|
||||
nft -f - >/dev/null 2>&1 <<NFT || true
|
||||
insert rule inet shellcrash input ip saddr $cidr accept comment "shellcrash-trusted"
|
||||
cidr="$(shellcrash_docker_cidr)"
|
||||
if ensure_ufw_shellcrash_docker_access "$port" "$proto" "$comment"; then
|
||||
ufw_rule_ok=1
|
||||
fi
|
||||
if have nft && nft list chain inet shellcrash input >/dev/null 2>&1; then
|
||||
if ! nft list chain inet shellcrash input 2>/dev/null | grep -Fq "ip saddr $cidr $proto dport $port accept"; then
|
||||
nft -f - >/dev/null 2>&1 <<NFT || true
|
||||
insert rule inet shellcrash input ip saddr $cidr $proto dport $port accept
|
||||
NFT
|
||||
fi
|
||||
fi
|
||||
if [ "$ufw_rule_ok" != "1" ] && have iptables; then
|
||||
iptables -C INPUT -s "$cidr" -p "$proto" --dport "$port" -j ACCEPT 2>/dev/null ||
|
||||
iptables -I INPUT -s "$cidr" -p "$proto" --dport "$port" -j ACCEPT 2>/dev/null || true
|
||||
fi
|
||||
done <<EOF
|
||||
$(shellcrash_trusted_cidrs)
|
||||
EOF
|
||||
fi
|
||||
if [ "$ufw_rule_ok" != "1" ] && have iptables; then
|
||||
iptables -C INPUT -s "$cidr" -p "$proto" --dport "$port" -j ACCEPT 2>/dev/null ||
|
||||
iptables -I INPUT -s "$cidr" -p "$proto" --dport "$port" -j ACCEPT 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
ensure_shellcrash_docker_proxy_access() {
|
||||
@ -1614,7 +1420,6 @@ ensure_shellcrash_docker_transparent_access() {
|
||||
ensure_shellcrash_proxy_ports_for_docker() {
|
||||
ensure_shellcrash_docker_proxy_access "$(shellcrash_mix_port)"
|
||||
ensure_shellcrash_docker_transparent_access
|
||||
ensure_shellcrash_docker_port_access "$(shellcrash_cfg_port db_port 9999 2>/dev/null || echo 9999)" tcp "ShellCrash dashboard from trusted"
|
||||
if neko_shellcrash_proxy_enabled; then
|
||||
ensure_shellcrash_docker_proxy_access "$(shellcrash_neko_proxy_port)" "Neko ShellCrash proxy from Docker"
|
||||
fi
|
||||
@ -1645,91 +1450,43 @@ shellcrash_proxy_available() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# Port listening is not enough: proxycheap listener can accept CONNECT while upstream is dead.
|
||||
shellcrash_proxy_egress_ready() {
|
||||
local port="$1" url="${NETWORK_PROBE_GOOGLE_URL:-https://www.google.com/generate_204}"
|
||||
shellcrash_proxy_available "$port" || return 1
|
||||
if have curl; then
|
||||
curl -kfsSL --connect-timeout 3 --max-time 8 -x "http://127.0.0.1:${port}" -o /dev/null "$url" 2>/dev/null && return 0
|
||||
elif have wget; then
|
||||
env http_proxy="http://127.0.0.1:${port}" https_proxy="http://127.0.0.1:${port}" \
|
||||
wget -q --no-check-certificate --timeout=8 -O /dev/null "$url" 2>/dev/null && return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
neko_shellcrash_attach_disabled() {
|
||||
case "${SHELLCRASH_ATTACH_NEKO:-auto}" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# ENABLE_NEKO_BROWSER_PROXY=1 -> proxycheap listener (NEKO_SHELLCRASH_PROXY_PORT, default 7894).
|
||||
# ENABLE_NEKO_BROWSER_PROXY=0 -> ShellCrash mixed port (7890) when direct egress is blocked.
|
||||
# When the host already has soft-router/direct Google access, Neko stays on direct for both switch states.
|
||||
resolve_neko_browser_proxy_primary_port() {
|
||||
if neko_browser_proxy_switch_enabled; then
|
||||
shellcrash_neko_proxy_port
|
||||
else
|
||||
shellcrash_mix_port
|
||||
fi
|
||||
}
|
||||
|
||||
resolve_neko_browser_proxy_fallback_port() {
|
||||
if neko_browser_proxy_switch_enabled; then
|
||||
shellcrash_mix_port
|
||||
else
|
||||
shellcrash_neko_proxy_port
|
||||
fi
|
||||
}
|
||||
|
||||
resolve_neko_browser_proxy() {
|
||||
case "${NEKO_BROWSER_PROXY:-}" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
|
||||
neko_shellcrash_attach_disabled && printf '%s' "$NEKO_BROWSER_PROXY" && return 0
|
||||
printf '%s' "$NEKO_BROWSER_PROXY"
|
||||
return 0
|
||||
;;
|
||||
?*)
|
||||
if neko_browser_proxy_url_is_usable "$NEKO_BROWSER_PROXY"; then
|
||||
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_egress_ready "$shell_port"; then
|
||||
neko_proxy_url_for_port "$shell_port"
|
||||
return 0
|
||||
fi
|
||||
system_direct_global_ready && return 0
|
||||
else
|
||||
printf '%s' "$NEKO_BROWSER_PROXY"
|
||||
return 0
|
||||
fi
|
||||
printf '%s' "$NEKO_BROWSER_PROXY"
|
||||
return 0
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
neko_shellcrash_attach_disabled && return 0
|
||||
system_direct_global_ready && return 0
|
||||
local port fallback
|
||||
port="$(resolve_neko_browser_proxy_primary_port)"
|
||||
if shellcrash_proxy_egress_ready "$port"; then
|
||||
neko_browser_proxy_switch_enabled || return 0
|
||||
case "$SHELLCRASH_ATTACH_NEKO" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
local port
|
||||
port="$(shellcrash_neko_proxy_port)"
|
||||
if shellcrash_proxy_available "$port"; then
|
||||
neko_proxy_url_for_port "$port"
|
||||
return 0
|
||||
fi
|
||||
fallback="$(resolve_neko_browser_proxy_fallback_port)"
|
||||
if [ -n "$fallback" ] && [ "$fallback" != "$port" ] && shellcrash_proxy_egress_ready "$fallback"; then
|
||||
neko_proxy_url_for_port "$fallback"
|
||||
if system_direct_global_ready; then
|
||||
return 0
|
||||
fi
|
||||
shellcrash_autostart_if_needed >/dev/null 2>&1 || true
|
||||
for port in "$(resolve_neko_browser_proxy_primary_port)" "$(resolve_neko_browser_proxy_fallback_port)"; do
|
||||
[ -n "$port" ] || continue
|
||||
if shellcrash_proxy_egress_ready "$port"; then
|
||||
neko_proxy_url_for_port "$port"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
port="$(shellcrash_neko_proxy_port)"
|
||||
if shellcrash_proxy_available "$port"; then
|
||||
neko_proxy_url_for_port "$port"
|
||||
fi
|
||||
}
|
||||
|
||||
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
|
||||
@ -1737,17 +1494,6 @@ 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)" \
|
||||
&& ! shellcrash_proxy_available "$(shellcrash_mix_port)" \
|
||||
&& system_direct_global_ready; then
|
||||
case "${NEKO_BROWSER_PROXY:-}" in
|
||||
""|0|false|FALSE|off|OFF|none|NONE|direct|DIRECT) ;;
|
||||
*)
|
||||
stack_env_upsert NEKO_BROWSER_PROXY ""
|
||||
export NEKO_BROWSER_PROXY=""
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
service_neko_reconfigure >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
@ -1769,7 +1515,7 @@ shellcrash_set_cfg() {
|
||||
shellcrash_cpu_core() {
|
||||
case "$(uname -m)" in
|
||||
aarch64|arm64) printf '%s\n' arm64 ;;
|
||||
armv7l|armv7*|armhf|armv6l) printf '%s\n' armv7 ;;
|
||||
armv7l|armv7*) printf '%s\n' armv7 ;;
|
||||
x86_64|amd64) printf '%s\n' amd64 ;;
|
||||
*) printf '%s\n' "$(uname -m)" ;;
|
||||
esac
|
||||
@ -1792,96 +1538,15 @@ shellcrash_web_url() {
|
||||
printf 'http://%s:%s/ui/\n' "$(shellcrash_web_host)" "$(shellcrash_web_port)"
|
||||
}
|
||||
|
||||
# Strip removed keys and force dashboard/mixed listeners so :9999 is reachable.
|
||||
shellcrash_patch_runtime_yaml() {
|
||||
local file="$1"
|
||||
[ -s "$file" ] || return 1
|
||||
command -v python3 >/dev/null 2>&1 || return 0
|
||||
python3 - "$file" <<'PY' || true
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
path = Path(sys.argv[1])
|
||||
lines = []
|
||||
found_ec = found_mp = False
|
||||
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
if line.startswith("global-client-fingerprint:"):
|
||||
continue
|
||||
if line.startswith("external-controller:"):
|
||||
lines.append("external-controller: 0.0.0.0:9999")
|
||||
found_ec = True
|
||||
continue
|
||||
if line.startswith("mixed-port:"):
|
||||
lines.append("mixed-port: 7890")
|
||||
found_mp = True
|
||||
continue
|
||||
lines.append(line)
|
||||
if not found_ec:
|
||||
lines.append("external-controller: 0.0.0.0:9999")
|
||||
if not found_mp:
|
||||
lines.append("mixed-port: 7890")
|
||||
path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
|
||||
PY
|
||||
}
|
||||
|
||||
# Prefer jsdelivr when GitHub is blocked; CrashCore otherwise exits after failed MMDB download.
|
||||
ensure_shellcrash_geo_databases() {
|
||||
local sc="${SHELLCRASH_DIR:-/etc/ShellCrash}"
|
||||
local js="https://testingcf.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release"
|
||||
local dest name min sz
|
||||
mkdir -p "$sc"
|
||||
|
||||
_shellcrash_geo_download() {
|
||||
local url="$1" out="$2"
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
curl -fsSL --connect-timeout 20 --max-time 120 -o "$out" "$url" && return 0
|
||||
env -u http_proxy -u https_proxy -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u all_proxy \
|
||||
curl -fsSL --connect-timeout 20 --max-time 120 -o "$out" "$url" && return 0
|
||||
fi
|
||||
if command -v wget >/dev/null 2>&1; then
|
||||
wget -q --no-check-certificate -O "$out" "$url" && return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
for pair in "geosite.dat:GeoSite.dat:1000000" "geoip.dat:GeoIP.dat:1000000" "geoip.metadb:Country.mmdb:1000000"; do
|
||||
name="${pair%%:*}"
|
||||
dest="$sc/${pair#*:}"
|
||||
dest="${dest%:*}"
|
||||
min="${pair##*:}"
|
||||
if [ -s "$dest" ]; then
|
||||
sz="$(wc -c <"$dest" | tr -d '[:space:]')"
|
||||
case "$sz" in
|
||||
''|*[!0-9]*) ;;
|
||||
*) [ "$sz" -ge "$min" ] && continue ;;
|
||||
esac
|
||||
fi
|
||||
echo "Fetching ShellCrash geo database $name" >&2
|
||||
if _shellcrash_geo_download "$js/$name" "$dest.tmp"; then
|
||||
mv -f "$dest.tmp" "$dest"
|
||||
chmod 644 "$dest" 2>/dev/null || true
|
||||
else
|
||||
rm -f "$dest.tmp"
|
||||
echo "WARN: could not download ShellCrash $name" >&2
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
shellcrash_sync_runtime_config() {
|
||||
local src="${1:-$SHELLCRASH_DIR/yamls/config.yaml}"
|
||||
local dst="/tmp/ShellCrash/config.yaml"
|
||||
mkdir -p "$SHELLCRASH_DIR/yamls" /tmp/ShellCrash
|
||||
if [ -s "$src" ]; then
|
||||
shellcrash_patch_runtime_yaml "$src" || true
|
||||
install -m 0644 "$src" "$dst"
|
||||
shellcrash_patch_runtime_yaml "$dst" || true
|
||||
return 0
|
||||
fi
|
||||
if [ -s "$dst" ]; then
|
||||
shellcrash_patch_runtime_yaml "$dst" || true
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
[ -s "$dst" ]
|
||||
}
|
||||
|
||||
patch_shellcrash_dns_repair() {
|
||||
@ -1931,7 +1596,6 @@ PY
|
||||
}
|
||||
|
||||
shellcrash_prepare_runtime() {
|
||||
ensure_shellcrash_geo_databases || true
|
||||
if ! shellcrash_sync_runtime_config; then
|
||||
return 1
|
||||
fi
|
||||
@ -2626,10 +2290,10 @@ service_neko_status() {
|
||||
local port network_ok port_ok http_code runtime_ok
|
||||
instance_count="$(resolve_neko_instance_count)"
|
||||
total_count="$instance_count"
|
||||
target_nat1to1="$(resolve_neko_nat1to1)"
|
||||
if [ -n "$target_nat1to1" ] && [ "${NEKO_WEBRTC_NAT1TO1:-}" != "$target_nat1to1" ]; then
|
||||
NEKO_WEBRTC_NAT1TO1="$target_nat1to1"
|
||||
if ! neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then
|
||||
NEKO_WEBRTC_NAT1TO1="$(detect_preferred_lan_ip || true)"
|
||||
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")"
|
||||
@ -2711,7 +2375,6 @@ service_neko_start() {
|
||||
ensure_neko_browser_launcher_executable
|
||||
prepare_neko_profile_dirs_for_compose
|
||||
ensure_shellcrash_proxy_ports_for_docker >/dev/null 2>&1 || true
|
||||
ensure_neko_webrtc_ports_for_trusted_cidrs >/dev/null 2>&1 || true
|
||||
for idx in $(seq 1 "$instance_count"); do
|
||||
prof="$(resolve_neko_profile_dir_for_instance "$idx")"
|
||||
port="$(resolve_neko_http_port_for_instance "$idx")"
|
||||
@ -2729,10 +2392,6 @@ service_neko_start() {
|
||||
compose_file="$(render_neko_compose_file)"
|
||||
# shellcheck disable=SC2086
|
||||
compose_in_service_dir "$compose_file" up -d $service_names
|
||||
if ! verify_neko_instances_running "$instance_count"; then
|
||||
kv message "Neko start incomplete; UDP port conflict autofix may need reconfigure. Check CrashCore/ss -ulnp"
|
||||
exit 1
|
||||
fi
|
||||
kv message "Neko stack started (${instance_count} browser instances)"
|
||||
}
|
||||
|
||||
@ -2751,7 +2410,6 @@ service_neko_reconfigure() {
|
||||
sync_neko_host_assets
|
||||
prepare_neko_profile_dirs_for_compose
|
||||
ensure_shellcrash_proxy_ports_for_docker >/dev/null 2>&1 || true
|
||||
ensure_neko_webrtc_ports_for_trusted_cidrs >/dev/null 2>&1 || true
|
||||
for idx in $(seq 1 "$instance_count"); do
|
||||
service_names="${service_names} neko${idx}"
|
||||
done
|
||||
@ -2760,10 +2418,6 @@ service_neko_reconfigure() {
|
||||
# Recreate containers so WebRTC env changes take effect; profile volumes are left untouched.
|
||||
# shellcheck disable=SC2086
|
||||
compose_in_service_dir "$compose_file" up -d --force-recreate $service_names
|
||||
if ! verify_neko_instances_running "$instance_count"; then
|
||||
kv message "Neko reconfigure incomplete; inspect docker logs / ss -ulnp for UDP conflicts"
|
||||
exit 1
|
||||
fi
|
||||
kv message "Neko WebRTC config reapplied (${instance_count} browser instances)"
|
||||
}
|
||||
|
||||
@ -2805,7 +2459,7 @@ export_neko_env() {
|
||||
export NEKO_BROWSER_PROXY_BYPASS="${NEKO_BROWSER_PROXY_BYPASS:-$(neko_default_proxy_bypass)}"
|
||||
export NEKO_MANAGED_POLICIES="${NEKO_MANAGED_POLICIES:-1}"
|
||||
export NEKO_TAMPERMONKEY_REPAIR="${NEKO_TAMPERMONKEY_REPAIR:-1}"
|
||||
export NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52098}"
|
||||
export NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52099}"
|
||||
export NEKO_WEBRTC_UDP_RANGE_1="${NEKO_WEBRTC_UDP_RANGE_1:-$NEKO_WEBRTC_UDP_RANGE}"
|
||||
export NEKO_WEBRTC_UDP_RANGE_2="${NEKO_WEBRTC_UDP_RANGE_2:-52101-52199}"
|
||||
export NEKO_WEBRTC_UDP_RANGE_3="${NEKO_WEBRTC_UDP_RANGE_3:-52201-52299}"
|
||||
@ -2814,7 +2468,6 @@ export_neko_env() {
|
||||
export NEKO_WEBRTC_EPR_2="${NEKO_WEBRTC_EPR_2:-$NEKO_WEBRTC_UDP_RANGE_2}"
|
||||
export NEKO_WEBRTC_EPR_3="${NEKO_WEBRTC_EPR_3:-$NEKO_WEBRTC_UDP_RANGE_3}"
|
||||
export NEKO_ACCESS_MODE="${NEKO_ACCESS_MODE:-lan}"
|
||||
sync_neko_wireguard_remote_access 1 || true
|
||||
# Upstream n.eko images include STUN servers by default, and ICE Lite with ICE servers is unstable.
|
||||
# Keep full ICE on by default even if an older system-stack.env still contains NEKO_WEBRTC_ICELITE=1.
|
||||
if [ "${NEKO_FORCE_ICELITE:-0}" = "1" ]; then
|
||||
@ -2830,37 +2483,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 [ -z "${NEKO_WEBRTC_NAT1TO1:-}" ]; then
|
||||
target_nat1to1="$(resolve_neko_nat1to1 || true)"
|
||||
if [ -n "$target_nat1to1" ]; then
|
||||
stack_env_upsert NEKO_WEBRTC_NAT1TO1 "$target_nat1to1"
|
||||
export NEKO_WEBRTC_NAT1TO1="$target_nat1to1"
|
||||
fi
|
||||
if ! neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then
|
||||
export NEKO_WEBRTC_NAT1TO1="$(detect_preferred_lan_ip || true)"
|
||||
fi
|
||||
export NEKO_PLUGINS_ENABLED="${NEKO_PLUGINS_ENABLED:-true}"
|
||||
}
|
||||
|
||||
verify_neko_instances_running() {
|
||||
local count="${1:-}" idx name port state code failed=0
|
||||
[ -n "$count" ] || count="$(resolve_neko_instance_count)"
|
||||
sleep 2
|
||||
for idx in $(seq 1 "$count"); do
|
||||
name="live-neko-$idx"
|
||||
port="$(resolve_neko_http_port_for_instance "$idx")"
|
||||
state="$(docker_container_status "$name" || true)"
|
||||
code="$(neko_http_probe_code "$port")"
|
||||
if [[ "$state" != running* ]] || [ "$code" = "000" ]; then
|
||||
failed=1
|
||||
kv message "Neko instance ${idx} unhealthy state=${state:-missing} http=${code} port=${port}"
|
||||
if have docker; then
|
||||
docker inspect "$name" --format 'err={{.State.Error}} exit={{.State.ExitCode}}' 2>/dev/null || true
|
||||
docker logs --tail 30 "$name" 2>&1 | tail -20 || true
|
||||
fi
|
||||
fi
|
||||
done
|
||||
return "$failed"
|
||||
}
|
||||
|
||||
service_neko_stop() {
|
||||
if [ ! -f "$ROOT_DIR/tools/render_neko_compose.py" ]; then
|
||||
kv message "Neko compose missing"
|
||||
@ -2874,7 +2502,7 @@ service_neko_stop() {
|
||||
}
|
||||
|
||||
service_mitmproxy_status() {
|
||||
if [ "${ENABLE_MITMPROXY:-0}" != "1" ]; then
|
||||
if [ "${ENABLE_MITMPROXY:-1}" != "1" ]; then
|
||||
kv available 0
|
||||
kv running 0
|
||||
kv status unavailable
|
||||
@ -2910,7 +2538,7 @@ service_mitmproxy_stop() {
|
||||
}
|
||||
|
||||
service_vscode_server_status() {
|
||||
if [ "${ENABLE_VSCODE_SERVER:-0}" != "1" ]; then
|
||||
if [ "${ENABLE_VSCODE_SERVER:-1}" != "1" ]; then
|
||||
kv available 0
|
||||
kv running 0
|
||||
kv status unavailable
|
||||
@ -2946,7 +2574,7 @@ service_vscode_server_stop() {
|
||||
}
|
||||
|
||||
service_uptime_kuma_status() {
|
||||
if [ "${ENABLE_UPTIME_KUMA:-0}" != "1" ]; then
|
||||
if [ "${ENABLE_UPTIME_KUMA:-1}" != "1" ]; then
|
||||
kv available 0
|
||||
kv running 0
|
||||
kv status unavailable
|
||||
@ -2982,7 +2610,7 @@ service_uptime_kuma_stop() {
|
||||
}
|
||||
|
||||
service_pulseaudio_status() {
|
||||
if [ "${ENABLE_PULSEAUDIO:-0}" != "1" ]; then
|
||||
if [ "${ENABLE_PULSEAUDIO:-1}" != "1" ]; then
|
||||
kv available 0
|
||||
kv running 0
|
||||
kv status unavailable
|
||||
@ -3050,7 +2678,7 @@ service_kmscube_stop() {
|
||||
}
|
||||
|
||||
service_openclaw_status() {
|
||||
if [ "${ENABLE_OPENCLAW:-0}" != "1" ]; then
|
||||
if [ "${ENABLE_OPENCLAW:-1}" != "1" ]; then
|
||||
kv available 0
|
||||
kv running 0
|
||||
kv status unavailable
|
||||
@ -3087,7 +2715,7 @@ service_openclaw_stop() {
|
||||
}
|
||||
|
||||
service_homeassistant_status() {
|
||||
if [ "${ENABLE_HOMEASSISTANT:-0}" != "1" ]; then
|
||||
if [ "${ENABLE_HOMEASSISTANT:-1}" != "1" ]; then
|
||||
kv available 0
|
||||
kv running 0
|
||||
kv status unavailable
|
||||
@ -3311,7 +2939,7 @@ ensure_frigate_default_config() {
|
||||
}
|
||||
|
||||
service_frigate_status() {
|
||||
if [ "${ENABLE_FRIGATE:-0}" != "1" ]; then
|
||||
if [ "${ENABLE_FRIGATE:-1}" != "1" ]; then
|
||||
kv available 0
|
||||
kv running 0
|
||||
kv status unavailable
|
||||
@ -3361,7 +2989,7 @@ service_frigate_stop() {
|
||||
}
|
||||
|
||||
service_frigate_auto() {
|
||||
if [ "${ENABLE_FRIGATE:-0}" != "1" ] || [ "${FRIGATE_USB_AUTOSTART:-0}" != "1" ]; then
|
||||
if [ "${ENABLE_FRIGATE:-1}" != "1" ] || [ "${FRIGATE_USB_AUTOSTART:-1}" != "1" ]; then
|
||||
kv message "Frigate USB autostart disabled"
|
||||
return 0
|
||||
fi
|
||||
@ -3452,7 +3080,7 @@ ensure_ntfy_default_config() {
|
||||
}
|
||||
|
||||
service_ntfy_status() {
|
||||
if [ "${ENABLE_NTFY:-0}" != "1" ]; then
|
||||
if [ "${ENABLE_NTFY:-1}" != "1" ]; then
|
||||
kv available 0
|
||||
kv running 0
|
||||
kv status unavailable
|
||||
@ -3654,7 +3282,7 @@ redroid_container_matches_host_support() {
|
||||
}
|
||||
|
||||
service_redroid_status() {
|
||||
if [ "${ENABLE_REDROID:-0}" != "1" ]; then
|
||||
if [ "${ENABLE_REDROID:-1}" != "1" ]; then
|
||||
kv available 0
|
||||
kv running 0
|
||||
kv status unavailable
|
||||
@ -3693,7 +3321,7 @@ service_redroid_status() {
|
||||
}
|
||||
|
||||
service_redroid_start() {
|
||||
if [ "${ENABLE_REDROID:-0}" != "1" ]; then
|
||||
if [ "${ENABLE_REDROID:-1}" != "1" ]; then
|
||||
kv message "Set ENABLE_REDROID=1 first"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@ -1,65 +0,0 @@
|
||||
#!/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
|
||||
@ -62,38 +62,16 @@ interface_is_stale() {
|
||||
'
|
||||
}
|
||||
|
||||
refresh_neko_after_wireguard_restart() {
|
||||
local root="${LIVE_STACK_ROOT:-/opt/live/d2ypp}"
|
||||
local ctl="$root/scripts/linux/service_ctl.sh"
|
||||
local common="$root/scripts/linux/lib/common.sh"
|
||||
[ -f "$common" ] || return 0
|
||||
# shellcheck source=/dev/null
|
||||
. "$common"
|
||||
STACK_ENV="${LIVE_STACK_ENV:-$root/config/system-stack.env}"
|
||||
ROOT_DIR="$root"
|
||||
sync_neko_wireguard_remote_access 1 || return 0
|
||||
ensure_neko_webrtc_ports_for_trusted_cidrs >/dev/null 2>&1 || true
|
||||
[ -f "$ctl" ] || return 0
|
||||
command -v docker >/dev/null 2>&1 || return 0
|
||||
docker ps --format '{{.Names}}' 2>/dev/null | grep -q '^live-neko-' || return 0
|
||||
bash "$ctl" neko reconfigure >/dev/null 2>&1 || log "WARN: Neko reconfigure after WireGuard restart failed"
|
||||
}
|
||||
|
||||
restart_interface() {
|
||||
local iface="$1"
|
||||
if systemctl list-unit-files "wg-quick@${iface}.service" --no-legend 2>/dev/null | grep -q .; then
|
||||
systemctl restart "wg-quick@${iface}.service"
|
||||
elif systemctl list-units "wg-quick@${iface}.service" --no-legend 2>/dev/null | grep -q .; then
|
||||
systemctl restart "wg-quick@${iface}.service"
|
||||
elif command -v wg-quick >/dev/null 2>&1 && [ -f "/etc/wireguard/${iface}.conf" ]; then
|
||||
log "WARN: $iface unit missing; falling back to wg-quick down/up"
|
||||
wg-quick down "$iface" >/dev/null 2>&1 || true
|
||||
wg-quick up "$iface"
|
||||
else
|
||||
log "WARN: $iface is stale but wg-quick@${iface}.service is not installed"
|
||||
return 1
|
||||
fi
|
||||
refresh_neko_after_wireguard_restart || true
|
||||
}
|
||||
|
||||
watch_once() {
|
||||
|
||||
@ -266,8 +266,7 @@ case "${NEKO_BROWSER_PROXY:-}" in
|
||||
http://*|https://*)
|
||||
proxy_bypass="${NEKO_BROWSER_PROXY_BYPASS:-<-loopback>;localhost;127.0.0.1;::1;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;*.local;host.docker.internal}"
|
||||
proxy_flags="--proxy-server=${NEKO_BROWSER_PROXY} --proxy-bypass-list=${proxy_bypass}"
|
||||
# Avoid Google login cancel when HTTP goes via proxy but WebRTC STUN leaks LAN/Docker IP.
|
||||
quic_flags="--disable-quic --force-webrtc-ip-handling-policy=disable_non_proxied_udp --disable-features=WebRtcAllowInputVolumeAdjustment"
|
||||
quic_flags="--disable-quic"
|
||||
;;
|
||||
esac
|
||||
|
||||
|
||||
@ -5,9 +5,7 @@
|
||||
"ExtensionInstallBlocklist": [],
|
||||
"DownloadRestrictions": 0,
|
||||
"AllowFileSelectionDialogs": true,
|
||||
"URLAllowlist": [
|
||||
"file:///home/neko/Downloads/*"
|
||||
],
|
||||
"URLAllowlist": ["file:///home/neko/Downloads/*"],
|
||||
"DefaultCookiesSetting": 1,
|
||||
"RestoreOnStartup": 1,
|
||||
"AutoplayAllowed": true,
|
||||
@ -15,14 +13,8 @@
|
||||
"DefaultNotificationsSetting": 1,
|
||||
"VideoCaptureAllowed": true,
|
||||
"AudioCaptureAllowed": true,
|
||||
"VideoCaptureAllowedUrls": [
|
||||
"https://*.google.com/*",
|
||||
"https://*.youtube.com/*"
|
||||
],
|
||||
"AudioCaptureAllowedUrls": [
|
||||
"https://*.google.com/*",
|
||||
"https://*.youtube.com/*"
|
||||
],
|
||||
"VideoCaptureAllowedUrls": ["https://*.google.com/*", "https://*.youtube.com/*"],
|
||||
"AudioCaptureAllowedUrls": ["https://*.google.com/*", "https://*.youtube.com/*"],
|
||||
"DeveloperToolsAvailability": 1,
|
||||
"DefaultGeolocationSetting": 1,
|
||||
"3rdparty": {
|
||||
@ -30,7 +22,7 @@
|
||||
"dhdgffkkebhmkfjojejmpbldmpobfkfo": {
|
||||
"jsonImport": [
|
||||
{
|
||||
"hash": "1:b75c2df29e515233fce1ca146ab62fff6bcbbaa20f5d5a8c16aa8f8993b77b15",
|
||||
"hash": "1:3d96725f5c1273d7468c1d6007817449b2356c7a47f8dfd096e297ca65f348dd",
|
||||
"url": "http://127.0.0.1:18080/tampermonkey-provisioning.json",
|
||||
"haltOnError": false,
|
||||
"installAsSystemScripts": false
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -1,11 +1,12 @@
|
||||
// ==UserScript==
|
||||
// @name YouTube Studio Auto Dismiss
|
||||
// @namespace http://tampermonkey.net/
|
||||
// @version 2.2.0
|
||||
// @description 直播结束 endscreen 自动离开:读 a#dismiss-link 并 location.assign,避免 MouseEvent 风控
|
||||
// @version 1.1
|
||||
// @description 每5秒自动检测并点击 YouTube Studio 直播页面的 Dismiss 按钮,支持延迟加载
|
||||
// @author You
|
||||
// @match https://studio.youtube.com/*
|
||||
// @run-at document-idle
|
||||
// @match https://studio.youtube.com/channel/*/livestreaming
|
||||
// @match https://studio.youtube.com/video/*/livestreaming
|
||||
// @match https://studio.youtube.com/*/livestreaming
|
||||
// @license MIT
|
||||
// @grant none
|
||||
// @downloadURL https://update.greasyfork.org/scripts/557378/YouTube%20Studio%20Auto%20Dismiss.user.js
|
||||
@ -15,217 +16,57 @@
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
// 不要用 <script> 注入:Studio CSP 常会静默拦截,导致“脚本装了但不跑”。
|
||||
// @grant none 下直接跑即可操作 DOM / location。
|
||||
|
||||
if (window.__ytStudioAutoDismissV22__) return;
|
||||
window.__ytStudioAutoDismissV22__ = true;
|
||||
|
||||
const COOLDOWN_MS = 8000;
|
||||
const HUMAN_DELAY_MIN = 400;
|
||||
const HUMAN_DELAY_MAX = 1200;
|
||||
const POLL_MS = 1500;
|
||||
|
||||
let busy = false;
|
||||
let lastAt = 0;
|
||||
let lastHrefTried = "";
|
||||
|
||||
function log() {
|
||||
try {
|
||||
console.log.apply(console, ["[YT Auto Dismiss]"].concat([].slice.call(arguments)));
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
function rand(min, max) {
|
||||
return min + Math.floor(Math.random() * (max - min + 1));
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise(function (resolve) {
|
||||
setTimeout(resolve, ms);
|
||||
function triggerClick(el) {
|
||||
if (!el) return;
|
||||
const evt = new MouseEvent("click", {
|
||||
view: window,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
el.dispatchEvent(evt);
|
||||
console.log("Dismiss 按钮已点击:", el, "父元素:", el.parentElement);
|
||||
}
|
||||
|
||||
function visible(el) {
|
||||
if (!el || !el.getBoundingClientRect) return false;
|
||||
var s = window.getComputedStyle(el);
|
||||
if (s.display === "none" || s.visibility === "hidden" || Number(s.opacity) === 0) return false;
|
||||
var r = el.getBoundingClientRect();
|
||||
return r.width > 1 && r.height > 1;
|
||||
}
|
||||
function findDismiss(root = document) {
|
||||
const allElements = root.querySelectorAll("button");
|
||||
for (const el of allElements) {
|
||||
try {
|
||||
const text = el.innerText ? el.innerText.trim() : "";
|
||||
if (text === "Dismiss" && isElementVisible(el)) {
|
||||
console.log("找到 Dismiss 按钮:", el);
|
||||
return el;
|
||||
}
|
||||
|
||||
function queryDeep(selector, root) {
|
||||
root = root || document;
|
||||
try {
|
||||
var hit = root.querySelector(selector);
|
||||
if (hit) return hit;
|
||||
} catch (_) {}
|
||||
var nodes = [];
|
||||
try {
|
||||
nodes = root.querySelectorAll("*");
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
for (var i = 0; i < nodes.length; i++) {
|
||||
var el = nodes[i];
|
||||
if (!el.shadowRoot) continue;
|
||||
var nested = queryDeep(selector, el.shadowRoot);
|
||||
if (nested) return nested;
|
||||
if (el.shadowRoot) {
|
||||
const shadowBtn = findDismiss(el.shadowRoot);
|
||||
if (shadowBtn) return shadowBtn;
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("检查元素时出错:", error);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function findEndscreen() {
|
||||
return (
|
||||
queryDeep("ytls-stream-endscreen-renderer") ||
|
||||
(function () {
|
||||
var box = queryDeep("#endscreen-container");
|
||||
return box && box.closest ? box.closest("ytls-stream-endscreen-renderer") : null;
|
||||
})()
|
||||
);
|
||||
function isElementVisible(el) {
|
||||
const style = window.getComputedStyle(el);
|
||||
return style.display !== "none" && style.visibility !== "hidden" && el.offsetParent !== null;
|
||||
}
|
||||
|
||||
function findDismissTarget() {
|
||||
var host = findEndscreen();
|
||||
if (!host || !visible(host)) return null;
|
||||
|
||||
var link =
|
||||
host.querySelector("a#dismiss-link") ||
|
||||
host.querySelector("#dismiss-link") ||
|
||||
host.querySelector("#completion-buttons a[href]") ||
|
||||
null;
|
||||
|
||||
var btn =
|
||||
host.querySelector("#dismiss-button button") ||
|
||||
host.querySelector("ytcp-button#dismiss-button") ||
|
||||
host.querySelector("#dismiss-button") ||
|
||||
null;
|
||||
|
||||
if (!link && !btn) return null;
|
||||
if (link && !visible(link) && btn && !visible(btn)) return null;
|
||||
return { host: host, link: link, btn: btn };
|
||||
}
|
||||
|
||||
function resolveHref(link) {
|
||||
if (!link) return "";
|
||||
var raw = link.href || link.getAttribute("href") || "";
|
||||
if (!raw) return "";
|
||||
try {
|
||||
return new URL(raw, location.origin).href;
|
||||
} catch (_) {
|
||||
return raw;
|
||||
function checkAndClick() {
|
||||
const btn = findDismiss();
|
||||
if (btn) {
|
||||
triggerClick(btn);
|
||||
} else {
|
||||
console.log("未找到 Dismiss 按钮或按钮不可见");
|
||||
}
|
||||
}
|
||||
|
||||
function hideEndscreen(host) {
|
||||
try {
|
||||
host.setAttribute("hidden", "");
|
||||
host.style.setProperty("display", "none", "important");
|
||||
if (host.remove) host.remove();
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
if (document.readyState === "complete") {
|
||||
checkAndClick();
|
||||
} else {
|
||||
window.addEventListener("load", checkAndClick, { once: true });
|
||||
}
|
||||
|
||||
async function dismissOnce(reason) {
|
||||
if (busy) return false;
|
||||
if (Date.now() - lastAt < COOLDOWN_MS) return false;
|
||||
|
||||
var target = findDismissTarget();
|
||||
if (!target) return false;
|
||||
|
||||
var href = resolveHref(target.link);
|
||||
if (href && href === lastHrefTried && Date.now() - lastAt < COOLDOWN_MS) return false;
|
||||
|
||||
busy = true;
|
||||
lastAt = Date.now();
|
||||
lastHrefTried = href || lastHrefTried;
|
||||
|
||||
try {
|
||||
log(reason || "found endscreen", {
|
||||
href: href,
|
||||
path: location.pathname,
|
||||
});
|
||||
await sleep(rand(HUMAN_DELAY_MIN, HUMAN_DELAY_MAX));
|
||||
if (!findDismissTarget()) {
|
||||
log("endscreen disappeared before action");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 1) 首选:按原生 <a id="dismiss-link"> 导航(无合成 click)
|
||||
if (href) {
|
||||
try {
|
||||
var url = new URL(href);
|
||||
if (url.origin === location.origin) {
|
||||
log("location.assign", url.href);
|
||||
location.assign(url.href);
|
||||
return true;
|
||||
}
|
||||
} catch (err) {
|
||||
log("assign failed", String(err));
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 摘掉 endscreen
|
||||
if (hideEndscreen(target.host)) {
|
||||
await sleep(300);
|
||||
if (!findDismissTarget()) {
|
||||
log("removed endscreen node");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 3) 兜底原生 click(仅限 endscreen 内按钮)
|
||||
var clickEl =
|
||||
(target.btn && target.btn.querySelector && target.btn.querySelector("button")) ||
|
||||
target.btn ||
|
||||
target.link;
|
||||
if (clickEl && clickEl.click) {
|
||||
log("native click fallback");
|
||||
HTMLElement.prototype.click.call(clickEl);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function tick(reason) {
|
||||
dismissOnce(reason).catch(function (err) {
|
||||
log("error", String(err));
|
||||
});
|
||||
}
|
||||
|
||||
var observer = new MutationObserver(function () {
|
||||
clearTimeout(tick._t);
|
||||
tick._t = setTimeout(function () {
|
||||
tick("mutation");
|
||||
}, 200);
|
||||
});
|
||||
|
||||
try {
|
||||
observer.observe(document.documentElement, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: ["style", "class", "hidden", "href"],
|
||||
});
|
||||
} catch (_) {}
|
||||
|
||||
// SPA:从 dashboard 进直播页时 userscript 不一定重跑,靠轮询兜底
|
||||
setInterval(function () {
|
||||
tick("poll");
|
||||
}, POLL_MS);
|
||||
|
||||
window.addEventListener("yt-navigate-finish", function () {
|
||||
tick("yt-navigate-finish");
|
||||
});
|
||||
window.addEventListener("popstate", function () {
|
||||
tick("popstate");
|
||||
});
|
||||
|
||||
log("installed", location.href);
|
||||
tick("boot");
|
||||
setInterval(checkAndClick, 5000);
|
||||
})();
|
||||
|
||||
@ -500,9 +500,6 @@ def _normalize_shellcrash_yaml(content: str, target_node: str) -> tuple[str, dic
|
||||
if target_node and not target_node_found:
|
||||
warning = f"Target proxy node not found: {target_node}; kept manual proxy selections"
|
||||
|
||||
# Newer mihomo/meta cores reject this top-level key (use per-proxy client-fingerprint).
|
||||
data.pop("global-client-fingerprint", None)
|
||||
|
||||
data["allow-lan"] = True
|
||||
data["mode"] = "rule"
|
||||
data["mixed-port"] = _coerce_shellcrash_port(data.get("mixed-port") or data.get("port"))
|
||||
@ -537,7 +534,7 @@ async def apply_shellcrash_profile(
|
||||
|
||||
stage_path = SHELLCRASH_PROFILE_STAGE.with_name(rel.name or SHELLCRASH_PROFILE_STAGE.name)
|
||||
stage_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
stage_path.write_text(normalized, encoding="utf-8")
|
||||
stage_path.write_text(normalized, encoding="utf-8", newline="\n")
|
||||
with contextlib.suppress(OSError):
|
||||
stage_path.chmod(0o600)
|
||||
|
||||
|
||||
@ -119,44 +119,33 @@ def set_youtube_pro_channels(channels: list[dict[str, Any]]) -> None:
|
||||
|
||||
|
||||
def merge_youtube_pro_channels(channels: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Merge browser-synced channel rows without letting stale tabs clobber keys/URLs.
|
||||
|
||||
Existing server order is preserved so channel cards do not reshuffle when a
|
||||
stale tab posts a differently ordered list.
|
||||
"""
|
||||
"""Merge browser-synced channel rows without letting stale tabs clobber keys/URLs."""
|
||||
incoming = normalize_youtube_pro_channels(channels)
|
||||
existing = get_youtube_pro_channels()
|
||||
incoming_by_pm2 = {channel_pm2_name(row): row for row in incoming if isinstance(row, dict)}
|
||||
incoming_by_id = {str(row.get("id", "")).strip(): row for row in incoming if isinstance(row, dict)}
|
||||
existing_by_pm2 = {channel_pm2_name(row): row for row in existing if isinstance(row, dict)}
|
||||
existing_by_id = {str(row.get("id", "")).strip(): row for row in existing if isinstance(row, dict)}
|
||||
|
||||
merged: list[dict[str, Any]] = []
|
||||
seen_pm2: set[str] = set()
|
||||
seen_ids: set[str] = set()
|
||||
for row in incoming:
|
||||
pm2 = channel_pm2_name(row)
|
||||
cid = str(row.get("id", "")).strip()
|
||||
current = existing_by_pm2.get(pm2) or existing_by_id.get(cid)
|
||||
if current:
|
||||
next_row = {**row, **current}
|
||||
merged.append(next_row)
|
||||
else:
|
||||
merged.append(dict(row))
|
||||
seen_pm2.add(pm2)
|
||||
if cid:
|
||||
seen_ids.add(cid)
|
||||
|
||||
for row in existing:
|
||||
pm2 = channel_pm2_name(row)
|
||||
cid = str(row.get("id", "")).strip()
|
||||
remote = incoming_by_pm2.get(pm2) or incoming_by_id.get(cid)
|
||||
if remote:
|
||||
# Existing wins for overlapping fields (keeps keys/URLs from server).
|
||||
merged.append({**remote, **row})
|
||||
else:
|
||||
if pm2 and pm2 not in seen_pm2 and cid not in seen_ids:
|
||||
merged.append(dict(row))
|
||||
if pm2:
|
||||
seen_pm2.add(pm2)
|
||||
if cid:
|
||||
seen_ids.add(cid)
|
||||
|
||||
for row in incoming:
|
||||
pm2 = channel_pm2_name(row)
|
||||
cid = str(row.get("id", "")).strip()
|
||||
if (pm2 and pm2 in seen_pm2) or (cid and cid in seen_ids):
|
||||
continue
|
||||
merged.append(dict(row))
|
||||
if pm2:
|
||||
seen_pm2.add(pm2)
|
||||
if cid:
|
||||
seen_ids.add(cid)
|
||||
|
||||
merged = normalize_youtube_pro_channels(merged)
|
||||
set_youtube_pro_channels(merged)
|
||||
|
||||
@ -49,13 +49,6 @@ 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,
|
||||
summarize_relay_sessions,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/hub", tags=["无人直播系统"])
|
||||
|
||||
@ -173,8 +166,7 @@ def _youtube_url_lines_for_process(name: str) -> str:
|
||||
return ""
|
||||
try:
|
||||
_, url_path = resolve_youtube_style_config_paths(_repo_root, name)
|
||||
url_file = Path(url_path)
|
||||
return url_file.read_text(encoding="utf-8", errors="ignore") if url_file.is_file() else ""
|
||||
return url_path.read_text(encoding="utf-8", errors="ignore") if url_path.is_file() else ""
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
@ -543,69 +535,6 @@ 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/stats")
|
||||
async def hub_youtube_relay_sessions_stats(
|
||||
process: str = "",
|
||||
q: str = "",
|
||||
date_from: str = "",
|
||||
date_to: str = "",
|
||||
status: str = "",
|
||||
top_anchors: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
return await asyncio.to_thread(
|
||||
summarize_relay_sessions,
|
||||
process=process,
|
||||
q=q,
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
status=status,
|
||||
top_anchors=top_anchors,
|
||||
)
|
||||
|
||||
|
||||
@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()}
|
||||
|
||||
@ -49,27 +49,20 @@ def upsert_env_value(path: Path, key: str, value: str) -> bool:
|
||||
lines = []
|
||||
prefix = f"{key}="
|
||||
next_line = f"{key}={value}"
|
||||
kept: list[str] = []
|
||||
found = False
|
||||
changed = False
|
||||
for raw in lines:
|
||||
for idx, raw in enumerate(lines):
|
||||
if raw.strip().startswith(prefix):
|
||||
if not found:
|
||||
kept.append(next_line)
|
||||
found = True
|
||||
if raw != next_line:
|
||||
changed = True
|
||||
else:
|
||||
if raw != next_line:
|
||||
lines[idx] = next_line
|
||||
changed = True
|
||||
continue
|
||||
kept.append(raw)
|
||||
if not found:
|
||||
if kept and kept[-1].strip():
|
||||
kept.append("")
|
||||
kept.append(next_line)
|
||||
break
|
||||
else:
|
||||
if lines and lines[-1].strip():
|
||||
lines.append("")
|
||||
lines.append(next_line)
|
||||
changed = True
|
||||
if changed:
|
||||
path.write_text("\n".join(kept).rstrip() + "\n", encoding="utf-8")
|
||||
path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
|
||||
return changed
|
||||
|
||||
|
||||
|
||||
@ -79,12 +79,7 @@ def is_usable_neko_browser_proxy(url: str) -> bool:
|
||||
return False
|
||||
if lowered == "host.docker.internal":
|
||||
return True
|
||||
try:
|
||||
addr = ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
return False
|
||||
# Docker bridge, LAN Clash on Windows, or other RFC1918 HTTP proxies.
|
||||
return isinstance(addr, ipaddress.IPv4Address) and bool(addr.is_private)
|
||||
return is_usable_docker_bridge_ipv4(host)
|
||||
|
||||
|
||||
def sanitize_neko_browser_proxy(url: str) -> str:
|
||||
|
||||
@ -1,221 +0,0 @@
|
||||
"""Neko WebRTC UDP range helpers.
|
||||
|
||||
ShellCrash CrashCore (and similar) sometimes bind a UDP port inside the default
|
||||
Neko ICE range (e.g. 52099 inside 52000-52099). Docker then fails with
|
||||
``address already in use`` and leaves live-neko-N exited. Detect foreign holders
|
||||
and shrink/shift the published range before compose up.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
_SS_PORT_RE = re.compile(r":(\d+)\s")
|
||||
_PROC_RE = re.compile(r'users:\(\("([^"]+)"')
|
||||
|
||||
|
||||
def sanitize_env_text(value: str) -> str:
|
||||
return (value or "").replace("\r", "").strip()
|
||||
|
||||
|
||||
def parse_udp_range(value: str, default: str) -> tuple[int, int]:
|
||||
raw = sanitize_env_text(value) or default
|
||||
match = re.fullmatch(r"(\d+)\s*-\s*(\d+)", raw)
|
||||
if not match:
|
||||
match = re.fullmatch(r"(\d+)\s*-\s*(\d+)", default)
|
||||
if not match:
|
||||
raise ValueError(f"invalid udp range: {value!r}")
|
||||
start, end = int(match.group(1)), int(match.group(2))
|
||||
if end < start:
|
||||
start, end = end, start
|
||||
return start, end
|
||||
|
||||
|
||||
def format_udp_range(start: int, end: int) -> str:
|
||||
return f"{start}-{end}"
|
||||
|
||||
|
||||
def default_udp_range(idx: int) -> str:
|
||||
# End at .98 so the historically CrashCore-bound .99 is outside the default.
|
||||
if idx == 1:
|
||||
return "52000-52098"
|
||||
if idx == 2:
|
||||
return "52101-52199"
|
||||
if idx == 3:
|
||||
return "52201-52299"
|
||||
start = 52400 + ((idx - 4) * 100)
|
||||
return f"{start}-{start + 99}"
|
||||
|
||||
|
||||
def _ignore_process(name: str) -> bool:
|
||||
lowered = (name or "").lower()
|
||||
return lowered in {
|
||||
"docker-proxy",
|
||||
"docker",
|
||||
"dockerd",
|
||||
"containerd",
|
||||
"containerd-shim",
|
||||
"containerd-shim-runc-v2",
|
||||
}
|
||||
|
||||
|
||||
def list_foreign_udp_holders(start: int, end: int) -> dict[int, str]:
|
||||
"""Return {port: process} for UDP listeners in [start, end] not owned by Docker."""
|
||||
if start > end:
|
||||
return {}
|
||||
if os.environ.get("NEKO_SKIP_UDP_PORT_PROBE", "").strip() in {"1", "true", "yes", "on"}:
|
||||
return {}
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["ss", "-ulnpH"],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return {}
|
||||
holders: dict[int, str] = {}
|
||||
for line in (proc.stdout or "").splitlines():
|
||||
ports = [int(p) for p in _SS_PORT_RE.findall(line)]
|
||||
if not ports:
|
||||
continue
|
||||
proc_match = _PROC_RE.search(line)
|
||||
proc_name = proc_match.group(1) if proc_match else "unknown"
|
||||
if _ignore_process(proc_name):
|
||||
continue
|
||||
for port in ports:
|
||||
if start <= port <= end:
|
||||
holders[port] = proc_name
|
||||
return holders
|
||||
|
||||
|
||||
def fit_udp_range(start: int, end: int, blocked: set[int], *, min_ports: int = 16) -> tuple[int, int]:
|
||||
"""Keep start when possible; shrink end around foreign holders; else shift nearby."""
|
||||
width = max(1, end - start + 1)
|
||||
blocked_in = {p for p in blocked if start <= p <= end}
|
||||
if not blocked_in:
|
||||
return start, end
|
||||
|
||||
# Prefer keeping the original start and cutting before the first blocker.
|
||||
first_block = min(blocked_in)
|
||||
shrunk_end = first_block - 1
|
||||
if shrunk_end - start + 1 >= min_ports:
|
||||
return start, shrunk_end
|
||||
|
||||
# Search for a free window of the original width near the intended range.
|
||||
search_lo = max(1024, start - 200)
|
||||
search_hi = end + 800
|
||||
for cand_start in range(search_lo, search_hi + 1):
|
||||
cand_end = cand_start + width - 1
|
||||
if any(p in blocked for p in range(cand_start, cand_end + 1)):
|
||||
continue
|
||||
return cand_start, cand_end
|
||||
|
||||
# Last resort: largest prefix free from start.
|
||||
if shrunk_end >= start:
|
||||
return start, shrunk_end
|
||||
return start, start
|
||||
|
||||
|
||||
def upsert_env_file(path: Path, updates: dict[str, str]) -> None:
|
||||
"""Write KEY=VALUE with Unix newlines; strip any existing CR."""
|
||||
if not updates:
|
||||
return
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
raw = path.read_text(encoding="utf-8", errors="replace") if path.exists() else ""
|
||||
raw = raw.replace("\r\n", "\n").replace("\r", "\n")
|
||||
lines = raw.split("\n")
|
||||
# Drop trailing empty line artifact for rewrite; restore one at end.
|
||||
if lines and lines[-1] == "":
|
||||
lines = lines[:-1]
|
||||
seen: set[str] = set()
|
||||
out: list[str] = []
|
||||
for line in lines:
|
||||
matched = False
|
||||
for key, value in updates.items():
|
||||
if line.startswith(f"{key}=") or line.startswith(f"export {key}="):
|
||||
out.append(f"{key}={value}")
|
||||
seen.add(key)
|
||||
matched = True
|
||||
break
|
||||
if not matched:
|
||||
out.append(line)
|
||||
for key, value in updates.items():
|
||||
if key not in seen:
|
||||
out.append(f"{key}={value}")
|
||||
path.write_text("\n".join(out) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def apply_neko_udp_range_autofix(
|
||||
count: int,
|
||||
*,
|
||||
stack_env: Path | None = None,
|
||||
persist: bool = True,
|
||||
) -> list[dict[str, str]]:
|
||||
"""Adjust NEKO_WEBRTC_UDP_RANGE_* / EPR_* in os.environ; optionally persist.
|
||||
|
||||
Returns a list of change records for logging.
|
||||
"""
|
||||
changes: list[dict[str, str]] = []
|
||||
updates: dict[str, str] = {}
|
||||
# Collect all blocked ports across candidate ranges so shifted windows stay free.
|
||||
probe_lo, probe_hi = 52000, 53000
|
||||
blocked = set(list_foreign_udp_holders(probe_lo, probe_hi))
|
||||
|
||||
for idx in range(1, max(1, count) + 1):
|
||||
default = default_udp_range(idx)
|
||||
udp_key = f"NEKO_WEBRTC_UDP_RANGE_{idx}"
|
||||
epr_key = f"NEKO_WEBRTC_EPR_{idx}"
|
||||
# Fallbacks mirror bash / renderer precedence.
|
||||
raw_udp = (
|
||||
os.environ.get(udp_key)
|
||||
or (os.environ.get("NEKO_WEBRTC_UDP_RANGE") if idx == 1 else None)
|
||||
or default
|
||||
)
|
||||
start, end = parse_udp_range(raw_udp, default)
|
||||
# Re-probe exact window in case the wide probe missed a late bind.
|
||||
blocked.update(list_foreign_udp_holders(start, end))
|
||||
new_start, new_end = fit_udp_range(start, end, blocked)
|
||||
new_range = format_udp_range(new_start, new_end)
|
||||
old_range = format_udp_range(start, end)
|
||||
holders = {p: n for p, n in list_foreign_udp_holders(start, end).items()}
|
||||
if new_range != old_range:
|
||||
changes.append(
|
||||
{
|
||||
"instance": str(idx),
|
||||
"from": old_range,
|
||||
"to": new_range,
|
||||
"holders": ",".join(f"{p}={name}" for p, name in sorted(holders.items())),
|
||||
}
|
||||
)
|
||||
# Reserve chosen window so later instances do not collide when shifting.
|
||||
blocked.update(range(new_start, new_end + 1))
|
||||
os.environ[udp_key] = new_range
|
||||
os.environ[epr_key] = new_range
|
||||
updates[udp_key] = new_range
|
||||
updates[epr_key] = new_range
|
||||
if idx == 1:
|
||||
os.environ["NEKO_WEBRTC_UDP_RANGE"] = new_range
|
||||
os.environ["NEKO_WEBRTC_EPR"] = new_range
|
||||
updates["NEKO_WEBRTC_UDP_RANGE"] = new_range
|
||||
updates["NEKO_WEBRTC_EPR"] = new_range
|
||||
|
||||
if persist and stack_env is not None and updates:
|
||||
needs_write = bool(changes)
|
||||
if stack_env.exists():
|
||||
existing = stack_env.read_text(encoding="utf-8", errors="replace")
|
||||
if "\r" in existing:
|
||||
needs_write = True
|
||||
else:
|
||||
for key, value in updates.items():
|
||||
if not re.search(rf"^{re.escape(key)}={re.escape(value)}$", existing, re.M):
|
||||
needs_write = True
|
||||
break
|
||||
else:
|
||||
needs_write = True
|
||||
if needs_write:
|
||||
upsert_env_file(stack_env, updates)
|
||||
return changes
|
||||
@ -284,17 +284,6 @@ def _attach_mode(raw: str | None) -> str:
|
||||
return "auto"
|
||||
|
||||
|
||||
def shellcrash_listener_egress_ok(port: str | int, *, url: str = GOOGLE_204) -> bool:
|
||||
"""Return True when a ShellCrash mixed/listener port can reach global targets."""
|
||||
port_s = str(port or "").strip()
|
||||
if not port_s.isdigit():
|
||||
return False
|
||||
if not shellcrash_runtime().get("running"):
|
||||
return False
|
||||
result = _probe_url(url, proxy=f"http://127.0.0.1:{port_s}")
|
||||
return bool(result.get("ok"))
|
||||
|
||||
|
||||
def neko_browser_proxy_auto_desired(probe: dict[str, Any]) -> bool:
|
||||
"""Enable Neko browser proxy when direct Google/YouTube fails but ShellCrash proxy works."""
|
||||
if bool(probe.get("global_direct_ok")):
|
||||
|
||||
@ -918,25 +918,17 @@ def _upsert_stack_env_values(repo_root: Path, values: dict[str, str]) -> bool:
|
||||
for key, value in values.items():
|
||||
prefix = f"{key}="
|
||||
next_line = f"{key}={value}"
|
||||
kept: list[str] = []
|
||||
found = False
|
||||
for raw in lines:
|
||||
for idx, raw in enumerate(lines):
|
||||
if raw.strip().startswith(prefix):
|
||||
if not found:
|
||||
kept.append(next_line)
|
||||
found = True
|
||||
if raw != next_line:
|
||||
changed = True
|
||||
else:
|
||||
if raw != next_line:
|
||||
lines[idx] = next_line
|
||||
changed = True
|
||||
continue
|
||||
kept.append(raw)
|
||||
if not found:
|
||||
if kept and kept[-1].strip():
|
||||
kept.append("")
|
||||
kept.append(next_line)
|
||||
break
|
||||
else:
|
||||
if lines and lines[-1].strip():
|
||||
lines.append("")
|
||||
lines.append(next_line)
|
||||
changed = True
|
||||
lines = kept
|
||||
if changed:
|
||||
env_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
|
||||
return changed
|
||||
@ -1230,7 +1222,7 @@ def _wireguard_quality(
|
||||
|
||||
|
||||
def wireguard_runtime_status(*, repo_root: Path) -> dict[str, Any]:
|
||||
auto_neko = ensure_neko_browser_proxy_for_network(repo_root, restart=False)
|
||||
auto_neko = ensure_neko_browser_proxy_for_network(repo_root, restart=True)
|
||||
commands = {name: bool(shutil.which(name)) for name in ("wg", "wg-quick", "ip", "systemctl")}
|
||||
system_configs = _system_wireguard_configs()
|
||||
repo_configs = list_imported_wireguard_configs(repo_root)
|
||||
@ -1378,43 +1370,6 @@ def _resolve_neko_docker_host_ip() -> str:
|
||||
return sanitize_docker_host_ip(gw)
|
||||
|
||||
|
||||
def _neko_shellcrash_attach_disabled(env: dict[str, str]) -> bool:
|
||||
attach = str(env.get("SHELLCRASH_ATTACH_NEKO") or "auto").strip().lower()
|
||||
return attach in {"0", "false", "off", "none", "direct", "disable", "disabled"}
|
||||
|
||||
|
||||
def _resolve_neko_browser_proxy_url(env: dict[str, str], *, proxycheap_enabled: bool) -> str:
|
||||
if _neko_shellcrash_attach_disabled(env):
|
||||
return ""
|
||||
try:
|
||||
from src.network_preflight import system_network_probe
|
||||
|
||||
if bool(system_network_probe(include_proxy=False).get("global_direct_ok")):
|
||||
return ""
|
||||
except Exception:
|
||||
pass
|
||||
from src.neko_docker_host import build_neko_browser_proxy_url, sanitize_neko_browser_proxy
|
||||
|
||||
explicit = str(env.get("NEKO_BROWSER_PROXY") or "").strip()
|
||||
if explicit and explicit.lower() not in {"0", "false", "off", "none", "direct"}:
|
||||
resolved = sanitize_neko_browser_proxy(explicit)
|
||||
if resolved:
|
||||
return resolved
|
||||
docker_host_ip = _resolve_neko_docker_host_ip()
|
||||
neko_port = str(env.get("NEKO_SHELLCRASH_PROXY_PORT") or "7894").strip() or "7894"
|
||||
try:
|
||||
from src.network_preflight import shellcrash_runtime, shellcrash_listener_egress_ok
|
||||
|
||||
mix_port = str(shellcrash_runtime().get("mixed_port") or "7890").strip() or "7890"
|
||||
except Exception:
|
||||
mix_port = "7890"
|
||||
shellcrash_listener_egress_ok = None # type: ignore[assignment]
|
||||
port = neko_port if proxycheap_enabled else mix_port
|
||||
if proxycheap_enabled and shellcrash_listener_egress_ok is not None and not shellcrash_listener_egress_ok(neko_port):
|
||||
port = mix_port
|
||||
return build_neko_browser_proxy_url(docker_host_ip, port)
|
||||
|
||||
|
||||
def _neko_browser_proxy_status(repo_root: Path) -> dict[str, Any]:
|
||||
env = _read_stack_env(repo_root)
|
||||
enabled = _env_flag_enabled(env, "ENABLE_NEKO_BROWSER_PROXY", default=False)
|
||||
@ -1423,13 +1378,20 @@ def _neko_browser_proxy_status(repo_root: Path) -> dict[str, Any]:
|
||||
node = str(env.get("SHELLCRASH_NEKO_PROXY_NODE") or "proxycheap").strip() or "proxycheap"
|
||||
attach = str(env.get("SHELLCRASH_ATTACH_NEKO") or "auto").strip() or "auto"
|
||||
docker_host_ip = _resolve_neko_docker_host_ip()
|
||||
resolved = _resolve_neko_browser_proxy_url(env, proxycheap_enabled=enabled)
|
||||
try:
|
||||
from src.network_preflight import shellcrash_runtime
|
||||
resolved = ""
|
||||
if enabled:
|
||||
if explicit and explicit.lower() not in {"0", "false", "off", "none", "direct"}:
|
||||
from src.neko_docker_host import sanitize_neko_browser_proxy
|
||||
|
||||
mix_port = str(shellcrash_runtime().get("mixed_port") or "7890").strip() or "7890"
|
||||
except Exception:
|
||||
mix_port = "7890"
|
||||
resolved = sanitize_neko_browser_proxy(explicit)
|
||||
if not resolved and attach.lower() not in {"0", "false", "off", "none", "direct"}:
|
||||
from src.neko_docker_host import build_neko_browser_proxy_url
|
||||
|
||||
resolved = build_neko_browser_proxy_url(docker_host_ip, port)
|
||||
elif attach.lower() not in {"0", "false", "off", "none", "direct"}:
|
||||
from src.neko_docker_host import build_neko_browser_proxy_url
|
||||
|
||||
resolved = build_neko_browser_proxy_url(docker_host_ip, port)
|
||||
return {
|
||||
"enabled": enabled,
|
||||
"switch": "ENABLE_NEKO_BROWSER_PROXY",
|
||||
@ -1437,10 +1399,8 @@ def _neko_browser_proxy_status(repo_root: Path) -> dict[str, Any]:
|
||||
"explicit_proxy": explicit,
|
||||
"resolved_proxy": resolved,
|
||||
"docker_host_ip": docker_host_ip,
|
||||
"shellcrash_port": port if enabled else mix_port,
|
||||
"shellcrash_node": node if enabled else "default",
|
||||
"proxycheap_port": port,
|
||||
"fallback_port": mix_port,
|
||||
"shellcrash_port": port,
|
||||
"shellcrash_node": node,
|
||||
"attach_mode": attach,
|
||||
}
|
||||
|
||||
@ -1457,22 +1417,6 @@ def ensure_neko_browser_proxy_for_network(repo_root: Path, *, restart: bool = Tr
|
||||
probe = system_network_probe()
|
||||
if not neko_browser_proxy_auto_desired(probe):
|
||||
return {"applied": False, "reason": "not_needed", "mode": probe.get("mode")}
|
||||
neko_port = str(env.get("NEKO_SHELLCRASH_PROXY_PORT") or "7894").strip() or "7894"
|
||||
from src.network_preflight import shellcrash_listener_egress_ok
|
||||
|
||||
if not shellcrash_listener_egress_ok(neko_port):
|
||||
reconfigure: dict[str, Any] = {"ok": True, "skipped": True, "reason": "proxycheap_unhealthy"}
|
||||
if restart:
|
||||
reconfigure = _reconfigure_neko_containers(repo_root)
|
||||
status = _neko_browser_proxy_status(repo_root)
|
||||
return {
|
||||
"applied": bool(reconfigure.get("ok") and not reconfigure.get("skipped")),
|
||||
"reason": "direct_blocked_mixed_only",
|
||||
"enabled": False,
|
||||
"mode": probe.get("mode"),
|
||||
**status,
|
||||
"reconfigure": reconfigure,
|
||||
}
|
||||
result = configure_neko_browser_proxy(
|
||||
repo_root=repo_root,
|
||||
enabled=True,
|
||||
@ -1489,18 +1433,12 @@ def configure_neko_browser_proxy(
|
||||
restart: bool = True,
|
||||
manual: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
updates: dict[str, str] = {
|
||||
"ENABLE_NEKO_BROWSER_PROXY": "1" if enabled else "0",
|
||||
# Drop stale per-host bridge IP overrides so resolve_neko_browser_proxy recalculates.
|
||||
"NEKO_BROWSER_PROXY": "",
|
||||
}
|
||||
updates: dict[str, str] = {"ENABLE_NEKO_BROWSER_PROXY": "1" if enabled else "0"}
|
||||
if manual:
|
||||
updates["NEKO_BROWSER_PROXY_MANUAL"] = "1"
|
||||
changed = _upsert_stack_env_values(repo_root, updates)
|
||||
reconfigure: dict[str, Any] = {"ok": True, "skipped": True, "reason": "unchanged"}
|
||||
# Manual UI toggles must always re-render compose even when env values look unchanged
|
||||
# (e.g. duplicate keys were deduped but containers still carry stale proxy).
|
||||
if restart and (changed or manual):
|
||||
if restart and changed:
|
||||
reconfigure = _reconfigure_neko_containers(repo_root)
|
||||
status = _neko_browser_proxy_status(repo_root)
|
||||
return {
|
||||
@ -1553,23 +1491,4 @@ def apply_wireguard_config(
|
||||
result["applied"] = True
|
||||
result["system_path"] = str(target)
|
||||
result["status"] = wireguard_runtime_status(repo_root=repo_root)
|
||||
# Applying WG means overlay access is intended: switch Neko to remote NAT1TO1 when ready.
|
||||
try:
|
||||
env = _read_stack_env(repo_root)
|
||||
mode = _normalize_neko_access_mode(env.get("NEKO_ACCESS_MODE") or "lan")
|
||||
status = result.get("status") if isinstance(result.get("status"), dict) else None
|
||||
access = (status or {}).get("neko_access") if isinstance(status, dict) else None
|
||||
remote_ready = bool(isinstance(access, dict) and access.get("remote_ready"))
|
||||
if mode == "remote" or remote_ready:
|
||||
result["neko_access"] = configure_neko_wireguard_access(
|
||||
repo_root=repo_root,
|
||||
mode="remote",
|
||||
restart=False,
|
||||
status=status,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - WireGuard apply already succeeded
|
||||
result["neko_access_error"] = str(exc)
|
||||
allow_script = Path("/usr/local/sbin/shellcrash-allow-trusted.sh")
|
||||
if allow_script.is_file():
|
||||
_run_command(["bash", str(allow_script)], timeout=8.0)
|
||||
return result
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,116 +0,0 @@
|
||||
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
|
||||
@ -291,29 +291,6 @@ rules:
|
||||
self.assertIn("IP-CIDR,192.168.0.0/16,DIRECT,no-resolve", data["rules"])
|
||||
self.assertEqual(data["rules"][-1], "MATCH,PROXY")
|
||||
|
||||
def test_shellcrash_normalize_strips_removed_global_client_fingerprint(self) -> None:
|
||||
content = """
|
||||
global-client-fingerprint: chrome
|
||||
proxies:
|
||||
- name: manual-node
|
||||
type: http
|
||||
server: 127.0.0.1
|
||||
port: 8080
|
||||
client-fingerprint: chrome
|
||||
proxy-groups:
|
||||
- name: PROXY
|
||||
type: select
|
||||
proxies:
|
||||
- manual-node
|
||||
rules:
|
||||
- MATCH,PROXY
|
||||
"""
|
||||
normalized, _meta = _normalize_shellcrash_yaml(content, "manual-node")
|
||||
data = yaml.safe_load(normalized)
|
||||
self.assertNotIn("global-client-fingerprint", data)
|
||||
self.assertEqual(data["proxies"][0]["client-fingerprint"], "chrome")
|
||||
self.assertEqual(data["external-controller"], "0.0.0.0:9999")
|
||||
|
||||
def test_shellcrash_normalize_adds_neko_dedicated_listener(self) -> None:
|
||||
content = """
|
||||
proxies:
|
||||
@ -356,10 +333,6 @@ rules:
|
||||
|
||||
self.assertIn("shellcrash_sync_runtime_config()", script)
|
||||
self.assertIn("shellcrash_prepare_runtime()", script)
|
||||
self.assertIn("shellcrash_patch_runtime_yaml()", script)
|
||||
self.assertIn("ensure_shellcrash_geo_databases()", script)
|
||||
self.assertIn("global-client-fingerprint:", script)
|
||||
self.assertIn("external-controller: 0.0.0.0:9999", script)
|
||||
self.assertIn('install -m 0644 "$src" "$dst"', script)
|
||||
self.assertIn('local dst="/tmp/ShellCrash/config.yaml"', script)
|
||||
self.assertIn("ShellCrash config.yaml is missing; save/apply a YAML profile first", script)
|
||||
@ -374,10 +347,6 @@ rules:
|
||||
self.assertIn("SHELLCRASH_AUTO_START_ON_WEB_PANEL", script)
|
||||
self.assertIn("shellcrash_systemd_restart", script)
|
||||
self.assertIn("system_direct_global_ready()", common)
|
||||
self.assertIn("ensure_shellcrash_geo_databases()", common)
|
||||
self.assertIn("shellcrash_patch_runtime_yaml()", common)
|
||||
self.assertIn("TimeoutStartSec=600", common)
|
||||
self.assertIn("10.66.66.0/24", common)
|
||||
self.assertIn("shellcrash_should_autostart_on_direct_fail()", common)
|
||||
self.assertIn("SHELLCRASH_AUTOSTART", common)
|
||||
self.assertIn("SHELLCRASH_DOCKER_CIDR", common)
|
||||
|
||||
@ -92,30 +92,6 @@ class HubKvStoreTests(unittest.TestCase):
|
||||
|
||||
self.assertEqual([row["pm2Name"] for row in rows], ["youtube2__lane1", "youtube2__lane2"])
|
||||
|
||||
def test_youtube_pro_channel_merge_preserves_existing_order(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
with patch.object(hub_kv_store, "CONFIG_DIR", Path(tmp) / "config"):
|
||||
hub_kv_store.set_youtube_pro_channels(
|
||||
[
|
||||
{"id": "lane1", "name": "Lane 1", "pm2Name": "youtube2__lane1"},
|
||||
{"id": "lane2", "name": "Lane 2", "pm2Name": "youtube2__lane2"},
|
||||
{"id": "lane3", "name": "Lane 3", "pm2Name": "youtube2__lane3"},
|
||||
]
|
||||
)
|
||||
|
||||
rows = hub_kv_store.merge_youtube_pro_channels(
|
||||
[
|
||||
{"id": "lane3", "name": "Lane 3", "pm2Name": "youtube2__lane3"},
|
||||
{"id": "lane1", "name": "Lane 1", "pm2Name": "youtube2__lane1"},
|
||||
{"id": "lane4", "name": "Lane 4", "pm2Name": "youtube2__lane4"},
|
||||
]
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
[row["id"] for row in rows],
|
||||
["lane1", "lane2", "lane3", "lane4"],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -201,44 +201,6 @@ class InstallCommonShellTests(unittest.TestCase):
|
||||
self.assertIn("WARN: hardware probe failed; continuing", body)
|
||||
self.assertIn("return 0", body)
|
||||
|
||||
def test_live_http_proxy_configures_apt_and_docker_daemon(self) -> None:
|
||||
apt_body = self._function_body("configure_live_apt_proxy", "configure_docker_http_proxy")
|
||||
docker_body = self._function_body("configure_docker_http_proxy", "apply_live_http_proxy_env")
|
||||
apply_body = self._function_body("apply_live_http_proxy_env", "clear_live_http_proxy_env")
|
||||
clear_body = self._function_body("clear_live_http_proxy_env", "detect_wireguard_overlay_ip")
|
||||
self.assertIn("/etc/apt/apt.conf.d/99live-proxy", apt_body)
|
||||
self.assertIn("Acquire::http::Proxy", apt_body)
|
||||
self.assertIn('/etc/systemd/system/docker.service.d', docker_body)
|
||||
self.assertIn('http-proxy.conf', docker_body)
|
||||
self.assertIn('Environment="HTTP_PROXY=', docker_body)
|
||||
self.assertIn("systemctl daemon-reload", docker_body)
|
||||
self.assertIn("configure_live_apt_proxy", apply_body)
|
||||
self.assertIn("configure_docker_http_proxy", apply_body)
|
||||
self.assertIn("configure_live_apt_proxy", clear_body)
|
||||
self.assertIn("configure_docker_http_proxy", clear_body)
|
||||
|
||||
def test_docker_stack_reapplies_proxy_before_and_after_install(self) -> None:
|
||||
body = self._function_body("install_docker_stack", "prepare_python_runtime")
|
||||
self.assertGreaterEqual(body.count("configure_docker_http_proxy"), 3)
|
||||
|
||||
def test_neko_install_retries_after_docker_proxy_reapply(self) -> None:
|
||||
body = self._function_body("install_neko_browser", "install_redroid")
|
||||
self.assertIn("configure_docker_http_proxy", body)
|
||||
self.assertIn("re-applying Docker proxy and retrying once", body)
|
||||
self.assertIn("switching Neko access mode to remote", body)
|
||||
self.assertIn("detect_wireguard_overlay_ip", body)
|
||||
|
||||
|
||||
class InstallBootstrapProxyPassThroughTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.script = (ROOT / "install.sh").read_text(encoding="utf-8")
|
||||
|
||||
def test_install_profile_forwards_live_http_proxy(self) -> None:
|
||||
self.assertIn('LIVE_HTTP_PROXY="${LIVE_HTTP_PROXY:-}"', self.script)
|
||||
self.assertIn('LIVE_HTTPS_PROXY="${LIVE_HTTPS_PROXY:-}"', self.script)
|
||||
self.assertIn("LIVE_HTTP_PROXY, LIVE_HTTPS_PROXY, LIVE_NO_PROXY", self.script)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -208,43 +208,6 @@ class NekoConfigTests(unittest.TestCase):
|
||||
self.assertIn('"./no-managed-policies:/etc/chromium-browser/policies/managed:ro"', personal_rendered)
|
||||
self.assertIn('"./no-managed-policies:/etc/opt/chrome/policies/managed:ro"', personal_rendered)
|
||||
|
||||
def test_dynamic_neko_instances_inherit_shared_proxy_unless_per_instance_enabled(self) -> None:
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"render_neko_compose",
|
||||
ROOT / "tools" / "render_neko_compose.py",
|
||||
)
|
||||
self.assertIsNotNone(spec)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
assert spec and spec.loader
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"NEKO_BROWSER_PROXY": "http://host.docker.internal:7890",
|
||||
"NEKO_BROWSER_PROXY_2": "http://172.19.0.1:7895",
|
||||
"NEKO_SHELLCRASH_PROXY_PORT_2": "7895",
|
||||
"NEKO_BROWSER_PROXY_PER_INSTANCE": "0",
|
||||
},
|
||||
clear=False,
|
||||
):
|
||||
rendered = module.render(2)
|
||||
self.assertEqual(rendered.count('NEKO_BROWSER_PROXY: "http://host.docker.internal:7890"'), 2)
|
||||
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"ENABLE_NEKO_BROWSER_PROXY": "1",
|
||||
"NEKO_BROWSER_PROXY": "",
|
||||
"NEKO_SHELLCRASH_PROXY_PORT": "7894",
|
||||
"NEKO_BROWSER_PROXY_PER_INSTANCE": "1",
|
||||
},
|
||||
clear=False,
|
||||
):
|
||||
per_instance = module.render(2)
|
||||
self.assertIn('NEKO_BROWSER_PROXY: "http://host.docker.internal:7894"', per_instance)
|
||||
self.assertIn('NEKO_BROWSER_PROXY: "http://host.docker.internal:7895"', per_instance)
|
||||
|
||||
def test_neko_runtime_scripts_use_generated_compose(self) -> None:
|
||||
service_ctl = (ROOT / "scripts" / "linux" / "service_ctl.sh").read_text(encoding="utf-8")
|
||||
common = (ROOT / "scripts" / "linux" / "lib" / "common.sh").read_text(encoding="utf-8")
|
||||
@ -268,8 +231,6 @@ 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()",
|
||||
@ -317,14 +278,13 @@ class NekoConfigTests(unittest.TestCase):
|
||||
"neko_shellcrash_proxy_enabled()",
|
||||
"SHELLCRASH_NEKO_PROXY_NODE",
|
||||
"SHELLCRASH_DOCKER_CIDR",
|
||||
'insert rule inet shellcrash input ip saddr $cidr accept comment "shellcrash-trusted"',
|
||||
'ip saddr $cidr $proto dport $port accept',
|
||||
"docker_container_http_port_published()",
|
||||
"docker_container_network_attached()",
|
||||
"remove_unreachable_neko_containers",
|
||||
"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=",
|
||||
@ -360,7 +320,7 @@ class NekoConfigTests(unittest.TestCase):
|
||||
'ufw allow in proto "$proto" from "$cidr" to any port "$port" >/dev/null 2>&1',
|
||||
"''|*[!0-9]*) return 0 ;;",
|
||||
'if [ "$ufw_rule_ok" != "1" ] && have iptables; then',
|
||||
'insert rule inet shellcrash input ip saddr $cidr accept comment "shellcrash-trusted"',
|
||||
'insert rule inet shellcrash input ip saddr $cidr $proto dport $port accept',
|
||||
'ensure_shellcrash_docker_port_access "$(shellcrash_redir_port)" tcp "ShellCrash redir from Docker"',
|
||||
'ensure_shellcrash_docker_port_access "$(shellcrash_tproxy_port)" tcp "ShellCrash tproxy from Docker"',
|
||||
'ensure_shellcrash_docker_port_access "$(shellcrash_tproxy_port)" udp "ShellCrash tproxy from Docker"',
|
||||
@ -437,12 +397,6 @@ class NekoConfigTests(unittest.TestCase):
|
||||
self.assertEqual(payload["scripts"][0]["options"], {})
|
||||
decoded_source = base64.b64decode(payload["scripts"][0]["source"]).decode("utf-8")
|
||||
self.assertEqual(decoded_source, userscript_path.read_text(encoding="utf-8"))
|
||||
# Avoid YouTube Live risk-control: no synthetic MouseEvent clicks.
|
||||
self.assertIn("// @version 2.2.0", decoded_source)
|
||||
self.assertIn("location.assign", decoded_source)
|
||||
self.assertIn("a#dismiss-link", decoded_source)
|
||||
self.assertNotIn("new MouseEvent", decoded_source)
|
||||
self.assertNotIn("dispatchEvent(evt)", decoded_source)
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"render_tampermonkey_provisioning",
|
||||
@ -552,36 +506,6 @@ 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")
|
||||
@ -592,8 +516,9 @@ class NekoConfigTests(unittest.TestCase):
|
||||
self.assertIn("live-neko-ip-watch.service", common)
|
||||
self.assertIn("ExecStart=/bin/bash", common)
|
||||
self.assertIn("scripts/linux/neko_ip_watch.sh", common)
|
||||
self.assertIn("resolve_neko_nat1to1", watcher)
|
||||
self.assertNotIn('target="${NEKO_WEBRTC_NAT1TO1:-}"', watcher)
|
||||
self.assertIn("detect_preferred_lan_ip", watcher)
|
||||
self.assertIn('target="${NEKO_WEBRTC_NAT1TO1:-}"', watcher)
|
||||
self.assertIn('case "${NEKO_ACCESS_MODE:-lan}"', watcher)
|
||||
self.assertIn('bash "$SERVICE_CTL" neko reconfigure', watcher)
|
||||
self.assertIn("NEKO_IP_WATCH_INTERVAL", watcher)
|
||||
self.assertIn("service_neko_reconfigure()", (ROOT / "scripts" / "linux" / "service_ctl.sh").read_text(encoding="utf-8"))
|
||||
|
||||
@ -32,11 +32,6 @@ class NekoDockerHostTests(unittest.TestCase):
|
||||
def test_accepts_valid_browser_proxy(self) -> None:
|
||||
self.assertTrue(is_usable_neko_browser_proxy("http://host.docker.internal:7894"))
|
||||
self.assertTrue(is_usable_neko_browser_proxy("http://172.20.0.1:7894"))
|
||||
self.assertTrue(is_usable_neko_browser_proxy("http://192.168.21.36:7897"))
|
||||
self.assertEqual(
|
||||
sanitize_neko_browser_proxy("http://192.168.21.36:7897"),
|
||||
"http://192.168.21.36:7897",
|
||||
)
|
||||
self.assertEqual(
|
||||
build_neko_browser_proxy_url("invalid IP", "7894"),
|
||||
"http://host.docker.internal:7894",
|
||||
|
||||
@ -1,102 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
import importlib.util
|
||||
|
||||
|
||||
def _load():
|
||||
path = ROOT / "src" / "neko_webrtc_ports.py"
|
||||
spec = importlib.util.spec_from_file_location("neko_webrtc_ports", path)
|
||||
assert spec and spec.loader
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
class NekoWebrtcPortsTests(unittest.TestCase):
|
||||
def test_sanitize_strips_cr(self) -> None:
|
||||
mod = _load()
|
||||
self.assertEqual(mod.sanitize_env_text("9200\r"), "9200")
|
||||
self.assertEqual(mod.sanitize_env_text("52000-52099\r\n"), "52000-52099")
|
||||
|
||||
def test_fit_udp_range_shrinks_before_crashcore(self) -> None:
|
||||
mod = _load()
|
||||
start, end = mod.fit_udp_range(52000, 52099, {52099})
|
||||
self.assertEqual((start, end), (52000, 52098))
|
||||
|
||||
def test_fit_udp_range_shifts_when_prefix_too_small(self) -> None:
|
||||
mod = _load()
|
||||
blocked = set(range(52000, 52090))
|
||||
start, end = mod.fit_udp_range(52000, 52099, blocked, min_ports=16)
|
||||
self.assertGreaterEqual(end - start + 1, 16)
|
||||
self.assertTrue(all(p not in blocked for p in range(start, end + 1)))
|
||||
|
||||
def test_upsert_env_file_normalizes_crlf_and_updates(self) -> None:
|
||||
mod = _load()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "system-stack.env"
|
||||
path.write_bytes(b"FOO=1\r\nNEKO_WEBRTC_UDP_RANGE=52000-52099\r\n")
|
||||
mod.upsert_env_file(path, {"NEKO_WEBRTC_UDP_RANGE": "52000-52098", "NEKO_WEBRTC_EPR": "52000-52098"})
|
||||
text = path.read_bytes()
|
||||
self.assertNotIn(b"\r", text)
|
||||
decoded = text.decode("utf-8")
|
||||
self.assertIn("NEKO_WEBRTC_UDP_RANGE=52000-52098\n", decoded)
|
||||
self.assertIn("NEKO_WEBRTC_EPR=52000-52098\n", decoded)
|
||||
self.assertIn("FOO=1\n", decoded)
|
||||
|
||||
def test_autofix_updates_environ_when_52099_blocked(self) -> None:
|
||||
mod = _load()
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"NEKO_WEBRTC_UDP_RANGE": "52000-52099",
|
||||
"NEKO_WEBRTC_UDP_RANGE_1": "52000-52099",
|
||||
"NEKO_WEBRTC_EPR": "52000-52099",
|
||||
"NEKO_WEBRTC_EPR_1": "52000-52099",
|
||||
"NEKO_SKIP_UDP_PORT_PROBE": "1",
|
||||
},
|
||||
clear=False,
|
||||
):
|
||||
with patch.object(mod, "list_foreign_udp_holders", return_value={52099: "CrashCore"}):
|
||||
changes = mod.apply_neko_udp_range_autofix(2, stack_env=None, persist=False)
|
||||
self.assertEqual(os.environ["NEKO_WEBRTC_UDP_RANGE_1"], "52000-52098")
|
||||
self.assertEqual(os.environ["NEKO_WEBRTC_EPR_1"], "52000-52098")
|
||||
self.assertTrue(any(c["to"] == "52000-52098" for c in changes))
|
||||
|
||||
def test_renderer_strips_cr_from_ports(self) -> None:
|
||||
path = ROOT / "tools" / "render_neko_compose.py"
|
||||
spec = importlib.util.spec_from_file_location("render_neko_compose", path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"NEKO_IMAGE": "test-image",
|
||||
"NEKO_PROFILE_HOST_DIR": f"{tmp}/profile",
|
||||
"NEKO_HTTP_PORT": "9200\r",
|
||||
"NEKO_HTTP_PORT_1": "9200\r",
|
||||
"NEKO_WEBRTC_TCPMUX_1": "52300\r",
|
||||
"NEKO_WEBRTC_UDPMUX_1": "52300\r",
|
||||
"NEKO_WEBRTC_UDP_RANGE_1": "52000-52098\r",
|
||||
"NEKO_WEBRTC_EPR_1": "52000-52098\r",
|
||||
"NEKO_SKIP_UDP_PORT_PROBE": "1",
|
||||
},
|
||||
clear=False,
|
||||
):
|
||||
rendered = module.render(1)
|
||||
self.assertIn('"9200:8080"', rendered)
|
||||
self.assertNotIn("9200\\r", rendered)
|
||||
self.assertIn('"52000-52098:52000-52098/udp"', rendered)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -335,14 +335,6 @@ class VerifyLocalInstallTests(unittest.TestCase):
|
||||
self.assertEqual(verify_local_install.neko_required_count({"NEKO_INSTANCE_COUNT": "4"}), 4)
|
||||
self.assertEqual(verify_local_install.neko_required_count({"NEKO_INSTANCE_COUNT": "99"}), 64)
|
||||
|
||||
def test_live_ops_unpacked_extension_is_allowed(self) -> None:
|
||||
live_ops = b"/usr/bin/google-chrome\0--load-extension=/etc/neko/live-ops-extension\0"
|
||||
self.assertFalse(verify_local_install.cmdline_has_forbidden_standalone_extension(live_ops))
|
||||
legacy = b"/usr/bin/google-chrome\0--load-extension=/etc/neko/youtube-auto-dismiss-extension\0"
|
||||
self.assertTrue(verify_local_install.cmdline_has_forbidden_standalone_extension(legacy))
|
||||
other = b"/usr/bin/google-chrome\0--load-extension=/tmp/random-ext\0"
|
||||
self.assertTrue(verify_local_install.cmdline_has_forbidden_standalone_extension(other))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -264,26 +264,16 @@ class WireGuardConfigTests(unittest.TestCase):
|
||||
"NEKO_SHELLCRASH_PROXY_PORT=7894\nSHELLCRASH_NEKO_PROXY_NODE=proxycheap\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
direct_probe = {"global_direct_ok": True}
|
||||
blocked_probe = {"global_direct_ok": False}
|
||||
with patch("src.network_preflight.system_network_probe", return_value=direct_probe):
|
||||
status = configure_neko_browser_proxy(repo_root=repo, enabled=False, restart=False)
|
||||
status = configure_neko_browser_proxy(repo_root=repo, enabled=False, restart=False)
|
||||
self.assertFalse(status["enabled"])
|
||||
self.assertEqual(status["resolved_proxy"], "")
|
||||
|
||||
with patch("src.network_preflight.system_network_probe", return_value=blocked_probe):
|
||||
with patch("src.wireguard_config._reconfigure_neko_containers", return_value={"ok": True, "skipped": False}):
|
||||
enabled = configure_neko_browser_proxy(repo_root=repo, enabled=True, restart=True)
|
||||
with patch("src.wireguard_config._reconfigure_neko_containers", return_value={"ok": True, "skipped": False}):
|
||||
enabled = configure_neko_browser_proxy(repo_root=repo, enabled=True, restart=True)
|
||||
self.assertTrue(enabled["enabled"])
|
||||
self.assertEqual(enabled["resolved_proxy"], "http://host.docker.internal:7894")
|
||||
self.assertIn("ENABLE_NEKO_BROWSER_PROXY=1", env.read_text(encoding="utf-8"))
|
||||
self.assertIn("NEKO_BROWSER_PROXY_MANUAL=1", env.read_text(encoding="utf-8"))
|
||||
self.assertIn("NEKO_BROWSER_PROXY=\n", env.read_text(encoding="utf-8"))
|
||||
|
||||
with patch("src.network_preflight.system_network_probe", return_value=blocked_probe):
|
||||
shellcrash_off = configure_neko_browser_proxy(repo_root=repo, enabled=False, restart=False)
|
||||
self.assertFalse(shellcrash_off["enabled"])
|
||||
self.assertEqual(shellcrash_off["resolved_proxy"], "http://host.docker.internal:7890")
|
||||
|
||||
def test_neko_browser_proxy_auto_enables_when_shellcrash_only(self) -> None:
|
||||
from src.wireguard_config import ensure_neko_browser_proxy_for_network
|
||||
@ -304,40 +294,12 @@ class WireGuardConfigTests(unittest.TestCase):
|
||||
"mode": "shellcrash",
|
||||
}
|
||||
with patch("src.network_preflight.system_network_probe", return_value=probe):
|
||||
with patch("src.network_preflight.shellcrash_listener_egress_ok", return_value=True):
|
||||
with patch("src.wireguard_config._reconfigure_neko_containers", return_value={"ok": True, "skipped": False}):
|
||||
result = ensure_neko_browser_proxy_for_network(repo_root=repo, restart=True)
|
||||
with patch("src.wireguard_config._reconfigure_neko_containers", return_value={"ok": True, "skipped": False}):
|
||||
result = ensure_neko_browser_proxy_for_network(repo_root=repo, restart=True)
|
||||
self.assertTrue(result["applied"])
|
||||
self.assertTrue(result["enabled"])
|
||||
self.assertNotIn("NEKO_BROWSER_PROXY_MANUAL=1", env.read_text(encoding="utf-8"))
|
||||
|
||||
def test_neko_browser_proxy_auto_uses_mixed_when_proxycheap_dead(self) -> None:
|
||||
from src.wireguard_config import ensure_neko_browser_proxy_for_network
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
repo = Path(tmp)
|
||||
env = repo / "config" / "system-stack.env"
|
||||
env.parent.mkdir(parents=True)
|
||||
env.write_text(
|
||||
"ENABLE_NEKO_BROWSER_PROXY=0\nSHELLCRASH_ATTACH_NEKO=auto\nNEKO_SHELLCRASH_PROXY_PORT=7894\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
probe = {
|
||||
"global_direct_ok": False,
|
||||
"global_proxy_ok": True,
|
||||
"shellcrash": {"running": True, "mixed_port": "7890"},
|
||||
"shellcrash_policy": {"attach_neko_mode": "auto"},
|
||||
"mode": "shellcrash",
|
||||
}
|
||||
with patch("src.network_preflight.system_network_probe", return_value=probe):
|
||||
with patch("src.network_preflight.shellcrash_listener_egress_ok", return_value=False):
|
||||
with patch("src.wireguard_config._reconfigure_neko_containers", return_value={"ok": True, "skipped": False}) as reconf:
|
||||
result = ensure_neko_browser_proxy_for_network(repo_root=repo, restart=True)
|
||||
self.assertTrue(result["applied"])
|
||||
self.assertFalse(result["enabled"])
|
||||
self.assertEqual(result["reason"], "direct_blocked_mixed_only")
|
||||
reconf.assert_called_once()
|
||||
|
||||
def test_neko_browser_proxy_auto_skips_when_direct_ok(self) -> None:
|
||||
from src.wireguard_config import ensure_neko_browser_proxy_for_network
|
||||
|
||||
@ -358,26 +320,6 @@ class WireGuardConfigTests(unittest.TestCase):
|
||||
self.assertFalse(result["applied"])
|
||||
self.assertEqual(result["reason"], "not_needed")
|
||||
|
||||
def test_upsert_stack_env_dedupes_duplicate_keys(self) -> None:
|
||||
from src.wireguard_config import _read_stack_env, _upsert_stack_env_values
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
repo = Path(tmp)
|
||||
env = repo / "config" / "system-stack.env"
|
||||
env.parent.mkdir(parents=True)
|
||||
env.write_text(
|
||||
"ENABLE_NEKO_BROWSER_PROXY=0\n"
|
||||
"NEKO_BROWSER_PROXY_MANUAL=0\n"
|
||||
"ENABLE_NEKO_BROWSER_PROXY=1\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
changed = _upsert_stack_env_values(repo_root=repo, values={"ENABLE_NEKO_BROWSER_PROXY": "0"})
|
||||
self.assertTrue(changed)
|
||||
text = env.read_text(encoding="utf-8")
|
||||
self.assertEqual(text.count("ENABLE_NEKO_BROWSER_PROXY="), 1)
|
||||
self.assertIn("ENABLE_NEKO_BROWSER_PROXY=0", text)
|
||||
self.assertFalse(_read_stack_env(repo)["ENABLE_NEKO_BROWSER_PROXY"] == "1")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -1,253 +0,0 @@
|
||||
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,
|
||||
summarize_relay_sessions,
|
||||
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)
|
||||
|
||||
def test_summarize_relay_sessions_by_anchor_and_hour(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/111",
|
||||
source_room_id="111",
|
||||
stream_title="又系_柠檬茶_2026-08-01_10-00-00",
|
||||
db_path=db,
|
||||
)
|
||||
end_relay_session("youtube", reason="done", db_path=db)
|
||||
start_relay_session(
|
||||
process="youtube",
|
||||
anchor_name="又系_柠檬茶",
|
||||
source_url="https://live.douyin.com/111",
|
||||
source_room_id="111",
|
||||
stream_title="又系_柠檬茶_2026-08-02_22-00-00",
|
||||
db_path=db,
|
||||
)
|
||||
end_relay_session("youtube", reason="done", db_path=db)
|
||||
start_relay_session(
|
||||
process="youtube",
|
||||
anchor_name="樱桃炒饭",
|
||||
source_url="https://live.douyin.com/222",
|
||||
source_room_id="222",
|
||||
stream_title="樱桃炒饭_2026-08-03_15-00-00",
|
||||
db_path=db,
|
||||
)
|
||||
end_relay_session("youtube", reason="done", db_path=db)
|
||||
|
||||
# Force deterministic start hours for heatmap assertions.
|
||||
from src.youtube_live_store import _connect
|
||||
|
||||
conn = _connect(db)
|
||||
rows = conn.execute(
|
||||
"SELECT id, stream_title FROM youtube_relay_sessions ORDER BY id"
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
title = row["stream_title"]
|
||||
stamp = title.rsplit("_", 2)
|
||||
# title like name_YYYY-MM-DD_HH-MM-SS
|
||||
day = stamp[-2]
|
||||
hms = stamp[-1]
|
||||
ts = f"{day} {hms.replace('-', ':')}"
|
||||
from datetime import datetime
|
||||
|
||||
started = datetime.strptime(ts, "%Y-%m-%d %H:%M:%S").timestamp()
|
||||
conn.execute(
|
||||
"UPDATE youtube_relay_sessions SET started_at=?, ended_at=?, duration_seconds=?, push_date=? WHERE id=?",
|
||||
(started, started + 3600, 3600, day, row["id"]),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
summary = summarize_relay_sessions(process="youtube", db_path=db)
|
||||
self.assertEqual(summary["overview"]["sessions"], 3)
|
||||
self.assertEqual(summary["overview"]["unique_anchors"], 2)
|
||||
self.assertAlmostEqual(summary["overview"]["total_hours"], 3.0, places=2)
|
||||
top = summary["top_anchors"][0]
|
||||
self.assertEqual(top["anchor_name"], "又系_柠檬茶")
|
||||
self.assertEqual(top["sessions"], 2)
|
||||
self.assertEqual(summary["by_hour"]["starts"][10], 1)
|
||||
self.assertEqual(summary["by_hour"]["starts"][22], 1)
|
||||
self.assertEqual(summary["by_hour"]["starts"][15], 1)
|
||||
self.assertTrue(summary["insights"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -1,80 +0,0 @@
|
||||
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()
|
||||
@ -1,62 +0,0 @@
|
||||
#!/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"))
|
||||
@ -1,107 +0,0 @@
|
||||
#!/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"))
|
||||
@ -1,28 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,148 +0,0 @@
|
||||
#!/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)
|
||||
@ -1,34 +0,0 @@
|
||||
#!/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]}")
|
||||
@ -1,95 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deploy neko hardening scripts to 10.88.0.8 and smoke-check reconfigure."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
HOST, USER, PASS = "10.88.0.8", "eric", "4669805"
|
||||
REMOTE_BASE = "/opt/live/d2ypp"
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
FILES = [
|
||||
"src/neko_webrtc_ports.py",
|
||||
"tools/render_neko_compose.py",
|
||||
"scripts/linux/service_ctl.sh",
|
||||
"scripts/linux/lib/common.sh",
|
||||
"scripts/linux/neko_ip_watch.sh",
|
||||
"config/system-stack.env.example",
|
||||
"live-platform/config/defaults/services/neko.json",
|
||||
"tests/test_neko_webrtc_ports.py",
|
||||
]
|
||||
|
||||
|
||||
def run(c: paramiko.SSHClient, cmd: str, timeout: int = 120) -> 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
|
||||
if not local.exists():
|
||||
print("MISSING", rel)
|
||||
continue
|
||||
remote_tmp = f"/tmp/{Path(rel).name}.{stamp}"
|
||||
sftp.put(str(local), remote_tmp)
|
||||
remote = f"{REMOTE_BASE}/{rel}"
|
||||
sudo(c, f"mkdir -p $(dirname {remote}) && cp {remote_tmp} {remote} && chmod +x {remote} || chmod 644 {remote}")
|
||||
# Ensure LF on shell/python text after Windows SFTP
|
||||
sudo(c, f"sed -i 's/\\r$//' {remote}")
|
||||
print("uploaded", rel)
|
||||
sftp.close()
|
||||
|
||||
print("=== unit smoke on host ===")
|
||||
print(
|
||||
run(
|
||||
c,
|
||||
f"cd {REMOTE_BASE} && NEKO_SKIP_UDP_PORT_PROBE=1 python3 -m unittest tests.test_neko_webrtc_ports -v 2>&1 | tail -30",
|
||||
timeout=60,
|
||||
)
|
||||
)
|
||||
|
||||
print("=== neko reconfigure (uses autofix) ===")
|
||||
# Don't force recreate if already healthy — just re-render and verify status.
|
||||
# Use reconfigure only if we want to apply script path; containers already good.
|
||||
out = sudo(
|
||||
c,
|
||||
f"bash {REMOTE_BASE}/scripts/linux/service_ctl.sh neko status | head -20; "
|
||||
f"python3 {REMOTE_BASE}/tools/render_neko_compose.py --count 2 "
|
||||
f"--output {REMOTE_BASE}/services/neko/docker-compose.generated.yml "
|
||||
f"--stack-env {REMOTE_BASE}/config/system-stack.env 2>&1 | tail -20; "
|
||||
f"grep -E 'NEKO_WEBRTC_UDP_RANGE_1=|NEKO_WEBRTC_EPR_1=' {REMOTE_BASE}/config/system-stack.env; "
|
||||
f"grep -E '52000-|52101-' {REMOTE_BASE}/services/neko/docker-compose.generated.yml | head -10",
|
||||
timeout=120,
|
||||
)
|
||||
print(out[:5000])
|
||||
|
||||
print("=== health ===")
|
||||
print(
|
||||
run(
|
||||
c,
|
||||
"docker ps --format 'table {{.Names}}\t{{.Status}}' | grep neko; "
|
||||
"printf '9200='; curl -sS -m 5 -o /dev/null -w '%{http_code}' http://127.0.0.1:9200/; echo; "
|
||||
"printf '9201='; curl -sS -m 5 -o /dev/null -w '%{http_code}' http://127.0.0.1:9201/; echo",
|
||||
)
|
||||
)
|
||||
c.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@ -1,90 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,83 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,151 +0,0 @@
|
||||
#!/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")
|
||||
@ -1,121 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deploy relay-log analytics UI + API to 10.88.0.8 and restart live-console."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import posixpath
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
HOST, USER, PASS = "10.88.0.8", "eric", "4669805"
|
||||
REMOTE_BASE = "/opt/live/d2ypp"
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
|
||||
FILES = [
|
||||
"src/youtube_relay_log.py",
|
||||
"src/hub_routes.py",
|
||||
"web.py",
|
||||
"web-console/app/youtube-relay-log/page.tsx",
|
||||
"web-console/components/live-product/LiveYoutubeRelayLogView.tsx",
|
||||
"web-console/components/live-product/LiveYoutubeRelayLogCharts.tsx",
|
||||
"tests/test_youtube_relay_log.py",
|
||||
]
|
||||
|
||||
|
||||
def collect_files() -> list[str]:
|
||||
files = list(FILES)
|
||||
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", ".json", ".css", ".html", ".txt", ".js"}:
|
||||
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 = 180) -> tuple[int, str]:
|
||||
_, stdout, stderr = client.exec_command(
|
||||
"export LC_ALL=C.UTF-8 LANG=C.UTF-8; " + cmd,
|
||||
timeout=timeout,
|
||||
get_pty=True,
|
||||
)
|
||||
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 <= 8 or idx == len(files) or idx % 50 == 0:
|
||||
print(f" {idx}/{len(files)} {rel}")
|
||||
sftp.close()
|
||||
|
||||
steps = [
|
||||
f"rm -rf {REMOTE_BASE}/src/__pycache__ 2>/dev/null; echo cache_cleared",
|
||||
(
|
||||
f"cd {REMOTE_BASE} && python3 -m py_compile src/youtube_relay_log.py web.py src/hub_routes.py "
|
||||
f"&& python3 -m unittest tests.test_youtube_relay_log.YoutubeRelayLogTests.test_summarize_relay_sessions_by_anchor_and_hour -v "
|
||||
f"2>&1 | tail -20"
|
||||
),
|
||||
f"echo {PASS!r} | sudo -S -p '' systemctl restart live-console.service; echo restarted",
|
||||
"sleep 8",
|
||||
"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 12 'http://127.0.0.1:8001/hub/youtube/relay/sessions/stats?process=youtube&top_anchors=5' | head -c 1200; echo",
|
||||
(
|
||||
"curl -sS -m 20 -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}' | head -c 400; echo"
|
||||
),
|
||||
"curl -sS -m 12 'http://127.0.0.1:8001/hub/youtube/relay/sessions/stats?process=youtube&top_anchors=5' | head -c 1500; echo",
|
||||
"systemctl is-active live-console.service; journalctl -u live-console.service -n 12 --no-pager",
|
||||
]
|
||||
for step in steps:
|
||||
code, out = run(client, step, timeout=240)
|
||||
print(f"\n--- exit={code} ---\n{out.strip()[:2000]}")
|
||||
client.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@ -1,96 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,130 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,77 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,163 +0,0 @@
|
||||
#!/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.")
|
||||
@ -1,104 +0,0 @@
|
||||
#!/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")
|
||||
@ -1,26 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,17 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,34 +0,0 @@
|
||||
#!/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")
|
||||
@ -1,27 +0,0 @@
|
||||
#!/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])
|
||||
@ -1,35 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,33 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,95 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,57 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,109 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,48 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,67 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,68 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,62 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,74 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,44 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,57 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,66 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,76 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,55 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,106 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,42 +0,0 @@
|
||||
#!/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"))
|
||||
@ -1,42 +0,0 @@
|
||||
#!/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"))
|
||||
@ -1,79 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import io
|
||||
import posixpath
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
HOST, USER, PASS = "10.88.0.8", "eric", "4669805"
|
||||
REMOTE = "/opt/live/d2ypp"
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def main() -> int:
|
||||
files = [
|
||||
"web-console/components/live-product/LiveYoutubeRelayLogView.tsx",
|
||||
"web-console/components/live-product/LiveYoutubeRelayLogCharts.tsx",
|
||||
"src/youtube_relay_log.py",
|
||||
"src/hub_routes.py",
|
||||
"web.py",
|
||||
]
|
||||
out = REPO / "web-console" / "out"
|
||||
for p in out.rglob("*"):
|
||||
if p.is_file():
|
||||
files.append(str(p.relative_to(REPO)).replace("\\", "/"))
|
||||
files = sorted(set(files))
|
||||
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=20)
|
||||
sftp = c.open_sftp()
|
||||
|
||||
def mkdir_p(d: str) -> None:
|
||||
d = d.rstrip("/")
|
||||
cur = ""
|
||||
for part in [x for x in d.split("/") if x]:
|
||||
cur = f"{cur}/{part}" if cur else f"/{part}"
|
||||
try:
|
||||
sftp.stat(cur)
|
||||
except OSError:
|
||||
try:
|
||||
sftp.mkdir(cur)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
for rel in files:
|
||||
local = REPO / rel
|
||||
if not local.is_file():
|
||||
continue
|
||||
remote = f"{REMOTE}/{rel}"
|
||||
mkdir_p(posixpath.dirname(remote))
|
||||
data = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n")
|
||||
sftp.putfo(io.BytesIO(data), remote)
|
||||
sftp.close()
|
||||
print(f"uploaded {len(files)}")
|
||||
|
||||
def run(cmd: str, timeout: int = 120) -> str:
|
||||
_, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True)
|
||||
return (o.read() + e.read()).decode("utf-8", "replace")
|
||||
|
||||
print(run(f"echo {PASS!r} | sudo -S -p '' systemctl restart live-console.service"))
|
||||
time.sleep(9)
|
||||
print(run("curl -sf -m 5 http://127.0.0.1:8001/health; echo"))
|
||||
print(run("curl -sS -m 8 -o /dev/null -w 'page=%{http_code}\\n' http://127.0.0.1:8001/youtube-relay-log"))
|
||||
print(
|
||||
run(
|
||||
"curl -sS -m 10 'http://127.0.0.1:8001/hub/youtube/relay/sessions/stats?top_anchors=5' "
|
||||
"| python3 -c \"import sys,json; d=json.load(sys.stdin); print(d['overview']); "
|
||||
"print([(a['anchor_name'], a['sessions'], round(a['hours_total'],1)) for a in d['top_anchors']])\""
|
||||
)
|
||||
)
|
||||
c.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@ -14,11 +14,12 @@ if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
|
||||
def _load_standalone(module_name: str, relative: str):
|
||||
def _load_neko_docker_host_helpers():
|
||||
# Keep this renderer usable from Linux service scripts with system Python.
|
||||
# Importing src.* normally executes src/__init__.py, which pulls app deps.
|
||||
module_path = ROOT / relative
|
||||
spec = importlib.util.spec_from_file_location(module_name, module_path)
|
||||
# Importing src.neko_docker_host normally executes src/__init__.py, which
|
||||
# pulls app dependencies that are not required for compose rendering.
|
||||
module_path = ROOT / "src" / "neko_docker_host.py"
|
||||
spec = importlib.util.spec_from_file_location("_neko_docker_host_standalone", module_path)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError(f"Unable to load {module_path}")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@ -26,30 +27,23 @@ def _load_standalone(module_name: str, relative: str):
|
||||
return module
|
||||
|
||||
|
||||
_neko_docker_host = _load_standalone("_neko_docker_host_standalone", "src/neko_docker_host.py")
|
||||
_neko_webrtc_ports = _load_standalone("_neko_webrtc_ports_standalone", "src/neko_webrtc_ports.py")
|
||||
_neko_docker_host = _load_neko_docker_host_helpers()
|
||||
build_neko_browser_proxy_url = _neko_docker_host.build_neko_browser_proxy_url
|
||||
neko_extra_hosts_mapping = _neko_docker_host.neko_extra_hosts_mapping
|
||||
sanitize_docker_host_ip = _neko_docker_host.sanitize_docker_host_ip
|
||||
sanitize_neko_browser_proxy = _neko_docker_host.sanitize_neko_browser_proxy
|
||||
apply_neko_udp_range_autofix = _neko_webrtc_ports.apply_neko_udp_range_autofix
|
||||
default_udp_range = _neko_webrtc_ports.default_udp_range
|
||||
sanitize_env_text = _neko_webrtc_ports.sanitize_env_text
|
||||
|
||||
|
||||
def env(name: str, default: str) -> str:
|
||||
value = os.environ.get(name)
|
||||
if value in {None, ""}:
|
||||
return default
|
||||
# Windows/SFTP edits often inject CR; compose then fails with invalid hostPort.
|
||||
return sanitize_env_text(value) or default
|
||||
return value if value not in {None, ""} else default
|
||||
|
||||
|
||||
def env_enabled(name: str, default: bool = False) -> bool:
|
||||
raw = os.environ.get(name)
|
||||
if raw in {None, ""}:
|
||||
return default
|
||||
return sanitize_env_text(raw).lower() in {"1", "true", "yes", "on", "enable", "enabled"}
|
||||
return raw.strip().lower() in {"1", "true", "yes", "on", "enable", "enabled"}
|
||||
|
||||
|
||||
def q(value: str) -> str:
|
||||
@ -61,45 +55,21 @@ def instance_value(prefix: str, idx: int, default: str) -> str:
|
||||
|
||||
|
||||
def host_path(base: str, name: str) -> str:
|
||||
base = sanitize_env_text(base)
|
||||
base = base.strip()
|
||||
if base in {"", ".", "./"}:
|
||||
return f"./{name}"
|
||||
return f"{base.rstrip('/')}/{name}"
|
||||
|
||||
|
||||
def resolve_shared_browser_proxy(docker_host_ip: str) -> str:
|
||||
"""Match service_ctl resolve_neko_browser_proxy: use exported NEKO_BROWSER_PROXY when set."""
|
||||
browser_proxy = sanitize_neko_browser_proxy(env("NEKO_BROWSER_PROXY", ""))
|
||||
if browser_proxy:
|
||||
return browser_proxy
|
||||
if env_enabled("ENABLE_NEKO_BROWSER_PROXY", False):
|
||||
return build_neko_browser_proxy_url(
|
||||
docker_host_ip,
|
||||
env("NEKO_SHELLCRASH_PROXY_PORT", "7894"),
|
||||
)
|
||||
# service_ctl exports NEKO_BROWSER_PROXY before render when direct is blocked.
|
||||
return ""
|
||||
|
||||
|
||||
def resolve_instance_browser_proxy(
|
||||
idx: int,
|
||||
*,
|
||||
shared_proxy: str,
|
||||
docker_host_ip: str,
|
||||
per_instance_proxy: bool,
|
||||
proxy_port_base: int,
|
||||
) -> str:
|
||||
# Default install (9200) and dynamically added channels (9201+) share the same
|
||||
# proxy policy unless explicit per-instance proxycheap mode is enabled.
|
||||
if not per_instance_proxy or not env_enabled("ENABLE_NEKO_BROWSER_PROXY", False):
|
||||
return shared_proxy
|
||||
inst_proxy = sanitize_neko_browser_proxy(instance_value("NEKO_BROWSER_PROXY", idx, ""))
|
||||
if inst_proxy:
|
||||
return inst_proxy
|
||||
inst_proxy_port = instance_value("NEKO_SHELLCRASH_PROXY_PORT", idx, "")
|
||||
if inst_proxy_port:
|
||||
return build_neko_browser_proxy_url(docker_host_ip, inst_proxy_port)
|
||||
return build_neko_browser_proxy_url(docker_host_ip, str(proxy_port_base + idx - 1))
|
||||
def default_udp_range(idx: int) -> str:
|
||||
if idx == 1:
|
||||
return "52000-52099"
|
||||
if idx == 2:
|
||||
return "52101-52199"
|
||||
if idx == 3:
|
||||
return "52201-52299"
|
||||
start = 52400 + ((idx - 4) * 100)
|
||||
return f"{start}-{start + 99}"
|
||||
|
||||
|
||||
def render(count: int) -> str:
|
||||
@ -119,17 +89,18 @@ def render(count: int) -> str:
|
||||
container_home = env("NEKO_CONTAINER_HOME", f"/home/{container_user}")
|
||||
render_mode = env("NEKO_BROWSER_RENDER_MODE", "auto")
|
||||
docker_host_ip = sanitize_docker_host_ip(env("NEKO_DOCKER_HOST_IP", ""))
|
||||
browser_proxy = resolve_shared_browser_proxy(docker_host_ip)
|
||||
browser_proxy = sanitize_neko_browser_proxy(env("NEKO_BROWSER_PROXY", ""))
|
||||
if not browser_proxy and env_enabled("ENABLE_NEKO_BROWSER_PROXY", False):
|
||||
browser_proxy = build_neko_browser_proxy_url(
|
||||
docker_host_ip,
|
||||
env("NEKO_SHELLCRASH_PROXY_PORT", "7894"),
|
||||
)
|
||||
browser_proxy_bypass = env(
|
||||
"NEKO_BROWSER_PROXY_BYPASS",
|
||||
"<-loopback>;localhost;127.0.0.1;::1;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;"
|
||||
"172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;"
|
||||
"172.31.*;192.168.*;*.local;host.docker.internal",
|
||||
)
|
||||
# Optional: give each instance its own ShellCrash mixed port / proxy URL so Google
|
||||
# does not see multiple accounts logging in from one shared exit IP (proxycheap).
|
||||
per_instance_proxy = env_enabled("NEKO_BROWSER_PROXY_PER_INSTANCE", False)
|
||||
proxy_port_base = int(env("NEKO_SHELLCRASH_PROXY_PORT", "7894") or "7894")
|
||||
extra_hosts_line = f' - "{neko_extra_hosts_mapping(docker_host_ip)}"'
|
||||
supervisor_conf = env("NEKO_BROWSER_SUPERVISOR_CONF", "chromium.conf")
|
||||
tampermonkey_repair = env("NEKO_TAMPERMONKEY_REPAIR", "1")
|
||||
@ -163,15 +134,6 @@ def render(count: int) -> str:
|
||||
udp_range = instance_value("NEKO_WEBRTC_UDP_RANGE", idx, default_udp_range(idx))
|
||||
epr = instance_value("NEKO_WEBRTC_EPR", idx, udp_range)
|
||||
profile = instance_value("NEKO_PROFILE_HOST_DIR", idx, base_profile if idx == 1 else f"{base_profile}-{idx}")
|
||||
inst_proxy_port = instance_value("NEKO_SHELLCRASH_PROXY_PORT", idx, "")
|
||||
browser_proxy_i = resolve_instance_browser_proxy(
|
||||
idx,
|
||||
shared_proxy=browser_proxy,
|
||||
docker_host_ip=docker_host_ip,
|
||||
per_instance_proxy=per_instance_proxy,
|
||||
proxy_port_base=proxy_port_base,
|
||||
)
|
||||
_ = inst_proxy_port # kept for backward-compatible env keys in docs/tests
|
||||
lines.extend(
|
||||
[
|
||||
f" neko{idx}:",
|
||||
@ -207,7 +169,7 @@ def render(count: int) -> str:
|
||||
' NEKO_PLUGINS_DIR: "/etc/neko/plugins/"',
|
||||
f" NEKO_START_URL: {q(start_url)}",
|
||||
f" NEKO_BROWSER_RENDER_MODE: {q(render_mode)}",
|
||||
f" NEKO_BROWSER_PROXY: {q(browser_proxy_i)}",
|
||||
f" NEKO_BROWSER_PROXY: {q(browser_proxy)}",
|
||||
f" NEKO_BROWSER_PROXY_BYPASS: {q(browser_proxy_bypass)}",
|
||||
f" NEKO_MANAGED_POLICIES: {q('1' if managed_policies else '0')}",
|
||||
f" NEKO_TAMPERMONKEY_REPAIR: {q(tampermonkey_repair)}",
|
||||
@ -248,32 +210,8 @@ def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Render Neko docker compose")
|
||||
parser.add_argument("--count", type=int, required=True)
|
||||
parser.add_argument("--output", required=True)
|
||||
parser.add_argument(
|
||||
"--stack-env",
|
||||
default="",
|
||||
help="Optional system-stack.env path; UDP range autofix + CRLF normalize persist here",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-udp-autofix",
|
||||
action="store_true",
|
||||
help="Skip probing foreign UDP holders (CrashCore) before rendering",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
count = max(1, min(64, args.count))
|
||||
stack_env = Path(args.stack_env) if args.stack_env else None
|
||||
if stack_env and stack_env.exists():
|
||||
# Normalize CRLF on the whole file before compose uses sourced values again.
|
||||
text = stack_env.read_text(encoding="utf-8", errors="replace")
|
||||
if "\r" in text:
|
||||
stack_env.write_text(text.replace("\r\n", "\n").replace("\r", "\n"), encoding="utf-8")
|
||||
if not args.no_udp_autofix:
|
||||
changes = apply_neko_udp_range_autofix(count, stack_env=stack_env, persist=True)
|
||||
for change in changes:
|
||||
print(
|
||||
f"[neko-udp-autofix] instance={change['instance']} "
|
||||
f"{change['from']} -> {change['to']} holders={change.get('holders') or '-'}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
output = Path(args.output)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(render(count), encoding="utf-8")
|
||||
|
||||
@ -1,109 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,79 +0,0 @@
|
||||
#!/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()
|
||||
@ -1,95 +0,0 @@
|
||||
#!/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())
|
||||
@ -276,27 +276,6 @@ def verify_http(checks: list[dict[str, Any]], env: dict[str, str], *, timeout: f
|
||||
)
|
||||
|
||||
|
||||
ALLOWED_UNPACKED_EXTENSION_SUFFIXES = (b"/live-ops-extension",)
|
||||
|
||||
|
||||
def cmdline_has_forbidden_standalone_extension(cmdline: bytes) -> bool:
|
||||
"""Reject legacy YouTube unpacked extensions; allow Live Hub live-ops."""
|
||||
if b"youtube-auto-" + b"dismiss-extension" in cmdline:
|
||||
return True
|
||||
args = [arg for arg in cmdline.split(b"\0") if arg]
|
||||
for arg in args:
|
||||
if not arg.startswith(b"--load-extension="):
|
||||
continue
|
||||
for raw_path in arg.split(b"=", 1)[1].split(b","):
|
||||
path = raw_path.strip().rstrip(b"/")
|
||||
if not path:
|
||||
continue
|
||||
if any(path.endswith(suffix) for suffix in ALLOWED_UNPACKED_EXTENSION_SUFFIXES):
|
||||
continue
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def neko_required_count(env: dict[str, str]) -> int:
|
||||
max_count = max(2, min(64, env_int(env, "NEKO_MAX_INSTANCE_COUNT", 64)))
|
||||
return max(2, min(max_count, env_int(env, "NEKO_INSTANCE_COUNT", 2)))
|
||||
@ -545,18 +524,6 @@ def verify_neko(checks: list[dict[str, Any]], env: dict[str, str], *, timeout: f
|
||||
"python3 - <<'PY'\n"
|
||||
"import os\n"
|
||||
"skip = {os.getpid(), os.getppid()}\n"
|
||||
"allowed_suffixes = (b'/live-ops-extension',)\n"
|
||||
"def forbidden(cmdline):\n"
|
||||
" if b'youtube-auto-' + b'dismiss-extension' in cmdline:\n"
|
||||
" return True\n"
|
||||
" for arg in [a for a in cmdline.split(b'\\0') if a]:\n"
|
||||
" if not arg.startswith(b'--load-extension='):\n"
|
||||
" continue\n"
|
||||
" for raw in arg.split(b'=', 1)[1].split(b','):\n"
|
||||
" path = raw.strip().rstrip(b'/')\n"
|
||||
" if path and not any(path.endswith(sfx) for sfx in allowed_suffixes):\n"
|
||||
" return True\n"
|
||||
" return False\n"
|
||||
"for name in os.listdir('/proc'):\n"
|
||||
" if not name.isdigit() or int(name) in skip:\n"
|
||||
" continue\n"
|
||||
@ -564,7 +531,10 @@ def verify_neko(checks: list[dict[str, Any]], env: dict[str, str], *, timeout: f
|
||||
" cmdline = open(f'/proc/{name}/cmdline', 'rb').read()\n"
|
||||
" except OSError:\n"
|
||||
" continue\n"
|
||||
" if forbidden(cmdline):\n"
|
||||
" args = [arg for arg in cmdline.split(b'\\0') if arg]\n"
|
||||
" has_unpacked_ext = any(arg.startswith(b'--load-extension=') and arg.split(b'=', 1)[1].strip() for arg in args)\n"
|
||||
" has_legacy_youtube_ext = b'youtube-auto-' + b'dismiss-extension' in cmdline\n"
|
||||
" if has_unpacked_ext or has_legacy_youtube_ext:\n"
|
||||
" print(cmdline.replace(b'\\0', b' ').decode('utf-8', errors='replace'))\n"
|
||||
" raise SystemExit(1)\n"
|
||||
"print('no standalone youtube extension')\n"
|
||||
|
||||
@ -1,51 +0,0 @@
|
||||
#!/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())
|
||||
@ -1,125 +0,0 @@
|
||||
# YouTube Studio Auto-Dismiss via Windows UI Automation (trusted OS mouse click).
|
||||
# Use this instead of Tampermonkey synthetic MouseEvent clicks (isTrusted=false triggers player "Something went wrong").
|
||||
#
|
||||
# Usage:
|
||||
# powershell -ExecutionPolicy Bypass -File tools/youtube_studio_dismiss_uia.ps1
|
||||
# powershell -ExecutionPolicy Bypass -File tools/youtube_studio_dismiss_uia.ps1 -Once
|
||||
# powershell -ExecutionPolicy Bypass -File tools/youtube_studio_dismiss_uia.ps1 -PollSeconds 2
|
||||
|
||||
param(
|
||||
[double]$PollSeconds = 1.5,
|
||||
[switch]$Once,
|
||||
[int]$MaxClicks = 0
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
Add-Type -AssemblyName UIAutomationClient
|
||||
Add-Type -AssemblyName UIAutomationTypes
|
||||
|
||||
Add-Type @"
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class YtDismissMouse {
|
||||
[DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y);
|
||||
[DllImport("user32.dll")] public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, UIntPtr dwExtraInfo);
|
||||
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
|
||||
public const uint LEFTDOWN = 0x0002;
|
||||
public const uint LEFTUP = 0x0004;
|
||||
public static void Click(int x, int y) {
|
||||
SetCursorPos(x, y);
|
||||
System.Threading.Thread.Sleep(60 + (new Random().Next(0, 80)));
|
||||
mouse_event(LEFTDOWN, 0, 0, 0, UIntPtr.Zero);
|
||||
System.Threading.Thread.Sleep(35 + (new Random().Next(0, 40)));
|
||||
mouse_event(LEFTUP, 0, 0, 0, UIntPtr.Zero);
|
||||
}
|
||||
}
|
||||
"@
|
||||
|
||||
function Get-StudioWindow {
|
||||
$root = [System.Windows.Automation.AutomationElement]::RootElement
|
||||
$winCond = New-Object System.Windows.Automation.PropertyCondition(
|
||||
[System.Windows.Automation.AutomationElement]::ControlTypeProperty,
|
||||
[System.Windows.Automation.ControlType]::Window
|
||||
)
|
||||
$wins = $root.FindAll([System.Windows.Automation.TreeScope]::Children, $winCond)
|
||||
foreach ($w in $wins) {
|
||||
$name = $w.Current.Name
|
||||
if ($name -match 'YouTube Studio') { return $w }
|
||||
}
|
||||
foreach ($w in $wins) {
|
||||
if ($w.Current.Name -notmatch 'Google Chrome') { continue }
|
||||
$c = New-Object System.Windows.Automation.PropertyCondition(
|
||||
[System.Windows.Automation.AutomationElement]::NameProperty, 'Dismiss'
|
||||
)
|
||||
if ($w.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $c)) { return $w }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Find-DismissButton([System.Windows.Automation.AutomationElement]$win) {
|
||||
$and = New-Object System.Windows.Automation.AndCondition(
|
||||
(New-Object System.Windows.Automation.PropertyCondition(
|
||||
[System.Windows.Automation.AutomationElement]::NameProperty, 'Dismiss')),
|
||||
(New-Object System.Windows.Automation.PropertyCondition(
|
||||
[System.Windows.Automation.AutomationElement]::ControlTypeProperty,
|
||||
[System.Windows.Automation.ControlType]::Button))
|
||||
)
|
||||
return $win.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $and)
|
||||
}
|
||||
|
||||
function Has-RiskOverlay([System.Windows.Automation.AutomationElement]$win) {
|
||||
foreach ($name in @('Something went wrong', 'Try again')) {
|
||||
$c = New-Object System.Windows.Automation.PropertyCondition(
|
||||
[System.Windows.Automation.AutomationElement]::NameProperty, $name
|
||||
)
|
||||
if ($win.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $c)) { return $true }
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
function Click-DismissTrusted([System.Windows.Automation.AutomationElement]$btn) {
|
||||
$r = $btn.Current.BoundingRectangle
|
||||
if ($r.Width -le 0 -or $r.Height -le 0) { return $false }
|
||||
$jitterX = Get-Random -Minimum -3 -Maximum 4
|
||||
$jitterY = Get-Random -Minimum -2 -Maximum 3
|
||||
$x = [int]($r.X + ($r.Width / 2) + $jitterX)
|
||||
$y = [int]($r.Y + ($r.Height / 2) + $jitterY)
|
||||
Write-Host ("[{0}] Trusted mouse click Dismiss at ({1},{2}) class={3}" -f (Get-Date -Format 'HH:mm:ss'), $x, $y, $btn.Current.ClassName)
|
||||
[YtDismissMouse]::Click($x, $y)
|
||||
return $true
|
||||
}
|
||||
|
||||
Write-Host "YouTube Studio Dismiss UIA watcher started (trusted OS clicks)."
|
||||
Write-Host "Keep Studio livestream tab open. Ctrl+C to stop."
|
||||
$clicks = 0
|
||||
|
||||
while ($true) {
|
||||
try {
|
||||
$win = Get-StudioWindow
|
||||
if ($win) {
|
||||
if (Has-RiskOverlay $win) {
|
||||
Write-Host ("[{0}] Risk overlay detected (Something went wrong / Try again)." -f (Get-Date -Format 'HH:mm:ss'))
|
||||
}
|
||||
$btn = Find-DismissButton $win
|
||||
if ($btn -and $btn.Current.IsEnabled -and -not $btn.Current.IsOffscreen) {
|
||||
Start-Sleep -Milliseconds (Get-Random -Minimum 400 -Maximum 1200)
|
||||
if (Click-DismissTrusted $btn) {
|
||||
$clicks++
|
||||
Start-Sleep -Seconds 2
|
||||
$win2 = Get-StudioWindow
|
||||
if ($win2 -and (Has-RiskOverlay $win2)) {
|
||||
Write-Host "WARNING: risk overlay appeared after trusted click."
|
||||
} elseif ($win2 -and -not (Find-DismissButton $win2)) {
|
||||
Write-Host ("[{0}] Dismiss cleared OK." -f (Get-Date -Format 'HH:mm:ss'))
|
||||
}
|
||||
if ($Once) { break }
|
||||
if ($MaxClicks -gt 0 -and $clicks -ge $MaxClicks) { break }
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
Write-Host ("[{0}] watch error: {1}" -f (Get-Date -Format 'HH:mm:ss'), $_.Exception.Message)
|
||||
}
|
||||
if ($Once) { break }
|
||||
Start-Sleep -Seconds $PollSeconds
|
||||
}
|
||||
@ -1,3 +0,0 @@
|
||||
"use client";
|
||||
|
||||
export { default } from "@/components/live-product/LiveYoutubeRelayLogView";
|
||||
@ -80,7 +80,6 @@ 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";
|
||||
}
|
||||
|
||||
@ -946,21 +945,17 @@ export default function LiveControlApp() {
|
||||
const setNekoBrowserProxy = async (enabled: boolean) => {
|
||||
setBusy(`neko:proxy:${enabled ? "on" : "off"}`);
|
||||
try {
|
||||
const data = await fetchJson<{ neko_browser_proxy?: WireGuardRuntimeStatus["neko_browser_proxy"] }>("/hub/network/neko_browser_proxy", {
|
||||
await fetchJson<{ neko_browser_proxy?: WireGuardRuntimeStatus["neko_browser_proxy"] }>("/hub/network/neko_browser_proxy", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ enabled, restart: true }),
|
||||
});
|
||||
if (data.neko_browser_proxy) {
|
||||
setWgStatus((prev) => (prev ? { ...prev, neko_browser_proxy: data.neko_browser_proxy } : prev));
|
||||
}
|
||||
await refreshWireGuardStatus();
|
||||
await refreshSystemNetworkProbe();
|
||||
await refreshDashboard();
|
||||
notify(
|
||||
enabled
|
||||
? t("已开启 Neko proxycheap 代理(7894)", "Neko proxycheap proxy enabled (7894)")
|
||||
: t("已关闭 proxycheap,直连失败时将走 ShellCrash 7890", "Proxycheap off; ShellCrash 7890 when direct blocked"),
|
||||
? t("已开启 Neko 浏览器代理", "Neko browser proxy enabled")
|
||||
: t("已关闭 Neko 浏览器代理", "Neko browser proxy disabled"),
|
||||
);
|
||||
} catch (e) {
|
||||
notify((e as Error).message);
|
||||
@ -1710,7 +1705,7 @@ export default function LiveControlApp() {
|
||||
liveProcesses={processRows.length ? processRows : (dash?.live?.processes ?? [])}
|
||||
notify={notify}
|
||||
quickLinks={ql}
|
||||
onRefresh={() => void Promise.all([refreshDashboard(), refreshProcessMonitor()])}
|
||||
onRefresh={() => refreshDashboard()}
|
||||
onNavigate={(target: PortalNavTarget) => setView(target)}
|
||||
/>
|
||||
) : null}
|
||||
@ -2539,7 +2534,7 @@ export default function LiveControlApp() {
|
||||
</div>
|
||||
<div className={`mt-3 rounded-lg border px-3 py-2 ${portalTheme === "light" ? "border-slate-200 bg-white" : "border-white/10 bg-black/20"}`}>
|
||||
<p className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
|
||||
{t("Neko proxycheap(7894)", "Neko proxycheap (7894)")}
|
||||
{t("Neko 浏览器代理", "Neko browser proxy")}
|
||||
</p>
|
||||
<div className={`mt-2 grid grid-cols-2 rounded-lg p-1 text-xs font-semibold ${portalTheme === "light" ? "bg-slate-200/70" : "bg-black/40"}`}>
|
||||
{([false, true] as const).map((enabled) => {
|
||||
@ -2560,7 +2555,7 @@ export default function LiveControlApp() {
|
||||
: "text-zinc-300 hover:bg-white/10"
|
||||
}`}
|
||||
>
|
||||
{enabled ? t("proxycheap", "proxycheap") : t("ShellCrash", "ShellCrash")}
|
||||
{enabled ? t("开启", "On") : t("关闭", "Off")}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
@ -2572,16 +2567,11 @@ export default function LiveControlApp() {
|
||||
<p>
|
||||
{t("节点", "Node")}: {wgStatus?.neko_browser_proxy?.shellcrash_node || "-"} · :{wgStatus?.neko_browser_proxy?.shellcrash_port || "7894"}
|
||||
</p>
|
||||
{systemNetworkProbe?.global_direct_ok ? (
|
||||
<p className={portalTheme === "light" ? "text-emerald-700" : "text-emerald-200"}>
|
||||
{t("宿主机可直连外网,Neko 不走 ShellCrash", "Host has direct egress; Neko stays direct")}
|
||||
</p>
|
||||
) : null}
|
||||
{systemNetworkProbe?.shellcrash_policy?.neko_browser_proxy_recommended &&
|
||||
!wgStatus?.neko_browser_proxy?.enabled &&
|
||||
!wgStatus?.neko_browser_proxy?.manual ? (
|
||||
<p className={portalTheme === "light" ? "text-cyan-700" : "text-cyan-200"}>
|
||||
{t("直连不可用,将自动开启 proxycheap(7894)", "Direct blocked; proxycheap (7894) will auto-enable")}
|
||||
{t("直连不可用且 ShellCrash 代理正常,将自动开启浏览器代理", "Direct egress failed; ShellCrash proxy is healthy — browser proxy will auto-enable")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@ -85,8 +85,6 @@ type Props = {
|
||||
monitorRow?: MonitorRowHint;
|
||||
/** Pro 线路名:推流中时固定显示频道名 */
|
||||
preferredTitle?: string;
|
||||
/** 隐藏进程/业务状态、转推指标、源站摘要等概览区,仅保留日志输出 */
|
||||
hideStatusOverview?: boolean;
|
||||
};
|
||||
|
||||
function businessLine(t: TFn, raw: string | undefined, note: string | undefined): string {
|
||||
@ -164,7 +162,6 @@ export function LiveProcessLiveLogCard({
|
||||
refreshToken = 0,
|
||||
monitorRow,
|
||||
preferredTitle,
|
||||
hideStatusOverview = false,
|
||||
}: Props) {
|
||||
const [processStatus, setProcessStatus] = useState<string>("");
|
||||
const [recentLog, setRecentLog] = useState("");
|
||||
@ -455,7 +452,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 && !hideStatusOverview ? (
|
||||
{pushingNow ? (
|
||||
<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" />
|
||||
@ -495,7 +492,6 @@ 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">
|
||||
@ -650,7 +646,6 @@ export function LiveProcessLiveLogCard({
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{processStatus !== "not_found" && processStatus !== "invalid" ? (
|
||||
<div className="mt-4 grid gap-4 lg:grid-cols-2">
|
||||
|
||||
@ -1,384 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
|
||||
export type RelayStats = {
|
||||
overview?: {
|
||||
sessions?: number;
|
||||
unique_anchors?: number;
|
||||
active_sessions?: number;
|
||||
total_hours?: number;
|
||||
avg_duration_seconds?: number;
|
||||
median_duration_seconds?: number;
|
||||
days_span?: number;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
};
|
||||
top_anchors?: Array<{
|
||||
anchor_name?: string;
|
||||
sessions?: number;
|
||||
hours_total?: number;
|
||||
avg_duration_seconds?: number;
|
||||
peak_hour?: number;
|
||||
peak_weekday_label?: string;
|
||||
dates_active?: number;
|
||||
sessions_per_active_day?: number;
|
||||
avg_gap_hours?: number | null;
|
||||
source_room_id?: string;
|
||||
}>;
|
||||
by_hour?: { starts?: number[]; minutes?: number[]; labels?: string[] };
|
||||
by_weekday?: { starts?: number[]; minutes?: number[]; labels?: string[]; labels_zh?: string[] };
|
||||
heatmap?: {
|
||||
starts?: number[][];
|
||||
minutes?: number[][];
|
||||
weekday_labels?: string[];
|
||||
weekday_labels_zh?: string[];
|
||||
hour_labels?: string[];
|
||||
};
|
||||
by_date?: Array<{ date: string; sessions: number; hours: number; unique_anchors: number }>;
|
||||
duration_buckets?: Record<string, number>;
|
||||
insights?: Array<{ zh: string; en: string }>;
|
||||
};
|
||||
|
||||
function useEchart(option: Record<string, unknown> | null, height: number) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el || !option) return;
|
||||
let disposed = false;
|
||||
let chart: import("echarts").ECharts | null = null;
|
||||
const onResize = () => chart?.resize();
|
||||
import("echarts").then((echarts) => {
|
||||
if (disposed || !ref.current) return;
|
||||
chart = echarts.init(ref.current, undefined, { renderer: "canvas" });
|
||||
chart.setOption(option, true);
|
||||
window.addEventListener("resize", onResize);
|
||||
});
|
||||
return () => {
|
||||
disposed = true;
|
||||
window.removeEventListener("resize", onResize);
|
||||
chart?.dispose();
|
||||
};
|
||||
}, [option]);
|
||||
return <div ref={ref} style={{ height }} className="w-full" />;
|
||||
}
|
||||
|
||||
const FG = "#f4f4f5";
|
||||
const MUTED = "#a1a1aa";
|
||||
const GRID = "rgba(255,255,255,0.06)";
|
||||
const TOOLTIP = {
|
||||
backgroundColor: "#18181b",
|
||||
borderColor: GRID,
|
||||
textStyle: { color: FG, fontSize: 12 },
|
||||
};
|
||||
|
||||
export function LiveYoutubeRelayLogCharts({
|
||||
stats,
|
||||
lang,
|
||||
t,
|
||||
}: {
|
||||
stats: RelayStats | null;
|
||||
lang: "zh" | "en";
|
||||
t: (zh: string, en: string) => string;
|
||||
}) {
|
||||
const overview = stats?.overview;
|
||||
const weekdayLabels = lang === "zh" ? stats?.by_weekday?.labels_zh || stats?.by_weekday?.labels : stats?.by_weekday?.labels;
|
||||
const heatWeekday = lang === "zh" ? stats?.heatmap?.weekday_labels_zh || stats?.heatmap?.weekday_labels : stats?.heatmap?.weekday_labels;
|
||||
|
||||
const dailyOption = useMemo(() => {
|
||||
const rows = stats?.by_date || [];
|
||||
if (!rows.length) return null;
|
||||
return {
|
||||
color: ["#22d3ee", "#a78bfa"],
|
||||
textStyle: { color: FG },
|
||||
tooltip: { ...TOOLTIP, trigger: "axis" },
|
||||
legend: { data: [t("场次", "Sessions"), t("时长(小时)", "Hours")], textStyle: { color: MUTED } },
|
||||
grid: { left: 48, right: 48, top: 40, bottom: 48 },
|
||||
xAxis: {
|
||||
type: "category",
|
||||
data: rows.map((r) => r.date.slice(5)),
|
||||
axisLabel: { color: MUTED, rotate: rows.length > 14 ? 45 : 0 },
|
||||
axisLine: { lineStyle: { color: GRID } },
|
||||
},
|
||||
yAxis: [
|
||||
{ type: "value", name: t("场次", "Sessions"), nameTextStyle: { color: MUTED }, axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
|
||||
{ type: "value", name: t("小时", "Hours"), nameTextStyle: { color: MUTED }, axisLabel: { color: MUTED }, splitLine: { show: false } },
|
||||
],
|
||||
series: [
|
||||
{ name: t("场次", "Sessions"), type: "bar", data: rows.map((r) => r.sessions), barMaxWidth: 18 },
|
||||
{ name: t("时长(小时)", "Hours"), type: "line", yAxisIndex: 1, smooth: true, data: rows.map((r) => Number(r.hours.toFixed(2))) },
|
||||
],
|
||||
};
|
||||
}, [stats?.by_date, t]);
|
||||
|
||||
const anchorOption = useMemo(() => {
|
||||
const rows = (stats?.top_anchors || []).slice(0, 12).reverse();
|
||||
if (!rows.length) return null;
|
||||
return {
|
||||
color: ["#34d399", "#38bdf8"],
|
||||
textStyle: { color: FG },
|
||||
tooltip: { ...TOOLTIP, trigger: "axis", axisPointer: { type: "shadow" } },
|
||||
legend: { data: [t("场次", "Sessions"), t("累计小时", "Hours")], textStyle: { color: MUTED } },
|
||||
grid: { left: 110, right: 48, top: 36, bottom: 28 },
|
||||
xAxis: { type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
|
||||
yAxis: {
|
||||
type: "category",
|
||||
data: rows.map((r) => (r.anchor_name || "—").slice(0, 14)),
|
||||
axisLabel: { color: MUTED, fontSize: 11 },
|
||||
axisLine: { lineStyle: { color: GRID } },
|
||||
},
|
||||
series: [
|
||||
{ name: t("场次", "Sessions"), type: "bar", data: rows.map((r) => r.sessions || 0), barMaxWidth: 14 },
|
||||
{ name: t("累计小时", "Hours"), type: "bar", data: rows.map((r) => Number((r.hours_total || 0).toFixed(2))), barMaxWidth: 14 },
|
||||
],
|
||||
};
|
||||
}, [stats?.top_anchors, t]);
|
||||
|
||||
const hourOption = useMemo(() => {
|
||||
const starts = stats?.by_hour?.starts || [];
|
||||
const minutes = stats?.by_hour?.minutes || [];
|
||||
if (!starts.some((n) => n > 0) && !minutes.some((n) => n > 0)) return null;
|
||||
return {
|
||||
color: ["#fbbf24", "#fb7185"],
|
||||
textStyle: { color: FG },
|
||||
tooltip: { ...TOOLTIP, trigger: "axis" },
|
||||
legend: { data: [t("开播次数", "Starts"), t("在播分钟", "On-air minutes")], textStyle: { color: MUTED } },
|
||||
grid: { left: 48, right: 48, top: 40, bottom: 36 },
|
||||
xAxis: {
|
||||
type: "category",
|
||||
data: stats?.by_hour?.labels || Array.from({ length: 24 }, (_, h) => `${String(h).padStart(2, "0")}:00`),
|
||||
axisLabel: { color: MUTED, fontSize: 10 },
|
||||
axisLine: { lineStyle: { color: GRID } },
|
||||
},
|
||||
yAxis: [
|
||||
{ type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
|
||||
{ type: "value", axisLabel: { color: MUTED }, splitLine: { show: false } },
|
||||
],
|
||||
series: [
|
||||
{ name: t("开播次数", "Starts"), type: "bar", data: starts, barMaxWidth: 12 },
|
||||
{ name: t("在播分钟", "On-air minutes"), type: "line", yAxisIndex: 1, smooth: true, areaStyle: { opacity: 0.12 }, data: minutes.map((n) => Number(n.toFixed(1))) },
|
||||
],
|
||||
};
|
||||
}, [stats?.by_hour, t]);
|
||||
|
||||
const weekdayOption = useMemo(() => {
|
||||
const starts = stats?.by_weekday?.starts || [];
|
||||
if (!starts.some((n) => n > 0)) return null;
|
||||
return {
|
||||
color: ["#818cf8"],
|
||||
textStyle: { color: FG },
|
||||
tooltip: { ...TOOLTIP, trigger: "axis" },
|
||||
grid: { left: 48, right: 16, top: 28, bottom: 36 },
|
||||
xAxis: {
|
||||
type: "category",
|
||||
data: weekdayLabels || [],
|
||||
axisLabel: { color: MUTED },
|
||||
axisLine: { lineStyle: { color: GRID } },
|
||||
},
|
||||
yAxis: { type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
|
||||
series: [{ type: "bar", data: starts, barMaxWidth: 28, name: t("开播场次", "Starts") }],
|
||||
};
|
||||
}, [stats?.by_weekday, weekdayLabels, t]);
|
||||
|
||||
const heatmapOption = useMemo(() => {
|
||||
const matrix = stats?.heatmap?.starts || [];
|
||||
if (!matrix.length) return null;
|
||||
const data: [number, number, number][] = [];
|
||||
let max = 0;
|
||||
matrix.forEach((row, wd) => {
|
||||
row.forEach((val, hour) => {
|
||||
data.push([hour, wd, val]);
|
||||
if (val > max) max = val;
|
||||
});
|
||||
});
|
||||
if (max <= 0) return null;
|
||||
return {
|
||||
textStyle: { color: FG },
|
||||
tooltip: {
|
||||
...TOOLTIP,
|
||||
formatter: (p: { data?: [number, number, number] }) => {
|
||||
const d = p.data;
|
||||
if (!d) return "";
|
||||
const hour = d[0];
|
||||
const wd = d[1];
|
||||
const label = (heatWeekday || [])[wd] || String(wd);
|
||||
return `${label} ${hour.toString().padStart(2, "0")}:00<br/>${t("开播", "Starts")}: <b>${d[2]}</b>`;
|
||||
},
|
||||
},
|
||||
grid: { left: 56, right: 24, top: 16, bottom: 40 },
|
||||
xAxis: {
|
||||
type: "category",
|
||||
data: stats?.heatmap?.hour_labels || Array.from({ length: 24 }, (_, h) => `${h}`),
|
||||
splitArea: { show: true },
|
||||
axisLabel: { color: MUTED, fontSize: 10 },
|
||||
},
|
||||
yAxis: {
|
||||
type: "category",
|
||||
data: heatWeekday || [],
|
||||
splitArea: { show: true },
|
||||
axisLabel: { color: MUTED },
|
||||
},
|
||||
visualMap: {
|
||||
min: 0,
|
||||
max: Math.max(1, max),
|
||||
calculable: true,
|
||||
orient: "horizontal",
|
||||
left: "center",
|
||||
bottom: 0,
|
||||
textStyle: { color: MUTED },
|
||||
inRange: { color: ["#18181b", "#0e7490", "#22d3ee", "#fbbf24", "#fb7185"] },
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: "heatmap",
|
||||
data,
|
||||
label: { show: false },
|
||||
emphasis: { itemStyle: { shadowBlur: 8, shadowColor: "rgba(0,0,0,0.4)" } },
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [stats?.heatmap, heatWeekday, t]);
|
||||
|
||||
const durationOption = useMemo(() => {
|
||||
const buckets = stats?.duration_buckets || {};
|
||||
const keys = Object.keys(buckets);
|
||||
if (!keys.length || !Object.values(buckets).some((n) => n > 0)) return null;
|
||||
return {
|
||||
color: ["#2dd4bf"],
|
||||
textStyle: { color: FG },
|
||||
tooltip: { ...TOOLTIP, trigger: "item" },
|
||||
series: [
|
||||
{
|
||||
type: "pie",
|
||||
radius: ["42%", "68%"],
|
||||
center: ["50%", "52%"],
|
||||
data: keys.map((k) => ({ name: k, value: buckets[k] })),
|
||||
label: { color: MUTED, formatter: "{b}\n{c}" },
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [stats?.duration_buckets]);
|
||||
|
||||
const dailyChart = useEchart(dailyOption, 280);
|
||||
const anchorChart = useEchart(anchorOption, 340);
|
||||
const hourChart = useEchart(hourOption, 280);
|
||||
const weekdayChart = useEchart(weekdayOption, 240);
|
||||
const heatChart = useEchart(heatmapOption, 300);
|
||||
const durationChart = useEchart(durationOption, 260);
|
||||
|
||||
if (!stats || !(overview?.sessions || 0)) {
|
||||
return (
|
||||
<div className="mb-4 rounded-xl border border-dashed border-white/10 bg-black/20 px-4 py-8 text-center text-sm text-zinc-500">
|
||||
{t("暂无统计数据。导入或积累推流记录后,这里会显示主播频率与时段规律。", "No analytics yet. Import or accumulate relay sessions to see patterns.")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const fmtDur = (seconds: number | undefined) => {
|
||||
const total = Math.max(0, Math.floor(Number(seconds) || 0));
|
||||
const h = Math.floor(total / 3600);
|
||||
const m = Math.floor((total % 3600) / 60);
|
||||
if (h > 0) return `${h}${t("小时", "h")}${m}${t("分", "m")}`;
|
||||
return `${m}${t("分", "m")}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mb-6 space-y-4">
|
||||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-6">
|
||||
{[
|
||||
[t("总场次", "Sessions"), String(overview?.sessions ?? 0)],
|
||||
[t("主播数", "Anchors"), String(overview?.unique_anchors ?? 0)],
|
||||
[t("累计时长", "Total hours"), `${Number(overview?.total_hours || 0).toFixed(1)}h`],
|
||||
[t("平均场长", "Avg length"), fmtDur(overview?.avg_duration_seconds)],
|
||||
[t("中位场长", "Median"), fmtDur(overview?.median_duration_seconds)],
|
||||
[t("进行中", "Active"), String(overview?.active_sessions ?? 0)],
|
||||
].map(([label, value]) => (
|
||||
<div key={label} className="rounded-xl border border-white/10 bg-gradient-to-br from-white/[0.06] to-transparent px-4 py-3">
|
||||
<div className="text-[11px] uppercase tracking-wide text-zinc-500">{label}</div>
|
||||
<div className="mt-1 text-xl font-semibold tabular-nums text-zinc-50">{value}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{stats.insights?.length ? (
|
||||
<div className="rounded-xl border border-cyan-500/20 bg-cyan-500/5 px-4 py-3 text-sm text-cyan-50/90">
|
||||
<div className="mb-1 text-xs font-medium uppercase tracking-wide text-cyan-300/80">{t("规律速览", "Pattern snapshot")}</div>
|
||||
<ul className="space-y-1 text-zinc-200">
|
||||
{stats.insights.map((item, idx) => (
|
||||
<li key={idx}>· {lang === "zh" ? item.zh : item.en}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
|
||||
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("每日推流频率与时长", "Daily session frequency & hours")}</h3>
|
||||
<p className="mb-2 text-xs text-zinc-500">{t("柱:当天开播场次;线:当天累计推流小时。", "Bars: sessions/day; line: total hours/day.")}</p>
|
||||
{dailyChart}
|
||||
</section>
|
||||
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
|
||||
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("主播排行(场次 / 累计小时)", "Anchor ranking (sessions / hours)")}</h3>
|
||||
<p className="mb-2 text-xs text-zinc-500">{t("看谁最常被转、谁播得最久。", "Who is relayed most often and longest.")}</p>
|
||||
{anchorChart}
|
||||
</section>
|
||||
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
|
||||
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("一天内时段分布", "Time-of-day distribution")}</h3>
|
||||
<p className="mb-2 text-xs text-zinc-500">{t("开播次数 vs 实际在播占用(分钟)。", "Start counts vs on-air occupancy (minutes).")}</p>
|
||||
{hourChart}
|
||||
</section>
|
||||
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
|
||||
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("星期分布", "Weekday distribution")}</h3>
|
||||
<p className="mb-2 text-xs text-zinc-500">{t("哪天更容易开播。", "Which weekdays see more starts.")}</p>
|
||||
{weekdayChart}
|
||||
</section>
|
||||
<section className="rounded-xl border border-white/10 bg-black/25 p-4 xl:col-span-2">
|
||||
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("星期 × 小时 热力图(开播次数)", "Weekday × hour heatmap (starts)")}</h3>
|
||||
<p className="mb-2 text-xs text-zinc-500">{t("颜色越亮表示该时段开播越频繁,适合找固定档期。", "Brighter = more frequent starts; useful for spotting fixed slots.")}</p>
|
||||
{heatChart}
|
||||
</section>
|
||||
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
|
||||
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("单场时长分布", "Duration distribution")}</h3>
|
||||
<p className="mb-2 text-xs text-zinc-500">{t("短场/长场比例。", "Short vs long session mix.")}</p>
|
||||
{durationChart}
|
||||
</section>
|
||||
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
|
||||
<h3 className="mb-3 text-sm font-medium text-zinc-200">{t("主播明细(可对照图表)", "Anchor detail")}</h3>
|
||||
<div className="max-h-[260px] overflow-auto">
|
||||
<table className="min-w-full text-left text-xs">
|
||||
<thead className="sticky top-0 bg-zinc-950 text-zinc-500">
|
||||
<tr>
|
||||
<th className="px-2 py-2">{t("主播", "Anchor")}</th>
|
||||
<th className="px-2 py-2">{t("场次", "N")}</th>
|
||||
<th className="px-2 py-2">{t("小时", "Hours")}</th>
|
||||
<th className="px-2 py-2">{t("日均场", "/day")}</th>
|
||||
<th className="px-2 py-2">{t("峰值", "Peak")}</th>
|
||||
<th className="px-2 py-2">{t("间隔", "Gap")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(stats.top_anchors || []).map((row) => (
|
||||
<tr key={`${row.anchor_name}-${row.source_room_id}`} className="border-t border-white/5 text-zinc-300">
|
||||
<td className="px-2 py-2 font-medium text-zinc-100">{row.anchor_name || "—"}</td>
|
||||
<td className="px-2 py-2 tabular-nums">{row.sessions ?? 0}</td>
|
||||
<td className="px-2 py-2 tabular-nums">{Number(row.hours_total || 0).toFixed(1)}</td>
|
||||
<td className="px-2 py-2 tabular-nums">{Number(row.sessions_per_active_day || 0).toFixed(2)}</td>
|
||||
<td className="px-2 py-2">
|
||||
{String(row.peak_hour ?? 0).padStart(2, "0")}:00
|
||||
{row.peak_weekday_label ? ` · ${row.peak_weekday_label}` : ""}
|
||||
</td>
|
||||
<td className="px-2 py-2 tabular-nums">
|
||||
{row.avg_gap_hours == null ? "—" : `${Number(row.avg_gap_hours).toFixed(1)}h`}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LiveYoutubeRelayLogCharts;
|
||||
@ -1,503 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { ExternalLink, Loader2, RefreshCw, Search } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { LiveYoutubeRelayLogCharts, type RelayStats } from "@/components/live-product/LiveYoutubeRelayLogCharts";
|
||||
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") || ""
|
||||
: "";
|
||||
|
||||
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 [stats, setStats] = useState<RelayStats | null>(null);
|
||||
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 [tab, setTab] = useState<"charts" | "list">("charts");
|
||||
const limit = 50;
|
||||
|
||||
const t = useCallback((zh: string, en: string) => tr(lang, zh, en), [lang]);
|
||||
|
||||
const filterParams = 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);
|
||||
return params;
|
||||
}, [process, q, dateFrom, dateTo, status]);
|
||||
|
||||
const queryString = useMemo(() => {
|
||||
const params = new URLSearchParams(filterParams);
|
||||
params.set("limit", String(limit));
|
||||
params.set("offset", String(offset));
|
||||
return params.toString();
|
||||
}, [filterParams, offset]);
|
||||
|
||||
const statsQuery = useMemo(() => {
|
||||
const params = new URLSearchParams(filterParams);
|
||||
params.set("top_anchors", "25");
|
||||
return params.toString();
|
||||
}, [filterParams]);
|
||||
|
||||
const loadSessions = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const [listData, statsData] = await Promise.all([
|
||||
fetchJsonResponse<{ sessions?: RelaySession[]; total?: number }>(
|
||||
`/hub/youtube/relay/sessions?${queryString}`,
|
||||
),
|
||||
fetchJsonResponse<RelayStats>(`/hub/youtube/relay/sessions/stats?${statsQuery}`),
|
||||
]);
|
||||
setSessions(listData.sessions || []);
|
||||
setTotal(Number(listData.total) || 0);
|
||||
setStats(statsData || null);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [queryString, statsQuery]);
|
||||
|
||||
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() || undefined,
|
||||
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(
|
||||
"图表展示每位主播的开播频率、时段规律与累计时长;列表保留逐场明细与截图,便于版权追溯。",
|
||||
"Charts show per-anchor frequency, time-of-day patterns, and hours; the table keeps per-session detail and covers for 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={t("全部线路(留空)", "All lanes (empty)")}
|
||||
/>
|
||||
</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="mb-4 flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTab("charts")}
|
||||
className={`rounded-lg px-3 py-1.5 text-sm ${
|
||||
tab === "charts" ? "bg-white/15 text-white" : "bg-white/5 text-zinc-400 hover:bg-white/10"
|
||||
}`}
|
||||
>
|
||||
{t("可视化分析", "Analytics")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTab("list")}
|
||||
className={`rounded-lg px-3 py-1.5 text-sm ${
|
||||
tab === "list" ? "bg-white/15 text-white" : "bg-white/5 text-zinc-400 hover:bg-white/10"
|
||||
}`}
|
||||
>
|
||||
{t("场次列表", "Session list")} ({total})
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{tab === "charts" ? <LiveYoutubeRelayLogCharts stats={stats} lang={lang} t={t} /> : null}
|
||||
|
||||
{tab === "list" ? (
|
||||
<>
|
||||
<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>
|
||||
</>
|
||||
) : null}
|
||||
</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, ScrollText, Square, Trash2 } from "lucide-react";
|
||||
import { Activity, AlertTriangle, Ban, Clock, Database, ExternalLink, Eye, History, Loader2, MonitorPlay, Play, Plus, Radio, RefreshCw, Square, Trash2 } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
@ -34,7 +34,6 @@ import {
|
||||
resolveYoutubeProChannelPm2,
|
||||
saveYoutubeProChannels,
|
||||
sanitizeYoutubePm2Name,
|
||||
stabilizeYoutubeProChannelOrder,
|
||||
type YoutubeProChannel,
|
||||
type YoutubeProChannelsSyncOptions,
|
||||
} from "@/lib/youtubeProChannels";
|
||||
@ -176,9 +175,8 @@ function resolveChannelPm2(channel: YoutubeProChannel): string {
|
||||
const MODE_KEY = "live-hub-youtube-mode-v1";
|
||||
const PRO_PM2_RESERVED = new Set(["douyin_youtube", "tiktok", "obs", "web"]);
|
||||
|
||||
/** 隐藏单频道/多频道切换条;默认多频道 Pro(改 false 可恢复切换) */
|
||||
const HIDE_YOUTUBE_MODE_TOGGLE = true;
|
||||
const DEFAULT_YOUTUBE_MODE: "single" | "pro" = "pro";
|
||||
/** UI 暂时隐藏「多频道 Pro」切换(DOM 与逻辑保留,改 false 即可恢复) */
|
||||
const HIDE_YOUTUBE_MULTI_PRO_TOGGLE = false;
|
||||
|
||||
/** UI 隐藏顶部「转播实况」概览卡(状态、指标网格、打开源站等) */
|
||||
const HIDE_YOUTUBE_RELAY_SNAPSHOT = true;
|
||||
@ -189,9 +187,6 @@ 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;
|
||||
@ -218,44 +213,34 @@ 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_starting";
|
||||
}
|
||||
|
||||
function procStartBlocked(row?: LiveProcRow): boolean {
|
||||
// PM2 already online (waiting_source / monitoring / …) must also lock Start —
|
||||
// otherwise Pro lane “开始” stays clickable after start until ffmpeg is_pushing.
|
||||
return isLivePushingRow(row) || pm2StatusOnline(row?.process_status);
|
||||
return (
|
||||
!!row?.is_pushing ||
|
||||
business === "streaming" ||
|
||||
business === "relay_slow" ||
|
||||
business === "source_stalled"
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function proLanePrimaryTitle(laneName: string): string {
|
||||
// 卡片顺序/身份必须稳定:始终用线路名做主标题,避免推流状态变化时与抖音源标题对调。
|
||||
return laneName.trim();
|
||||
}
|
||||
|
||||
function proLaneDouyinSubtitle(
|
||||
function proLanePrimaryTitle(
|
||||
laneName: string,
|
||||
row?: LiveProcRow,
|
||||
urlLines = "",
|
||||
laneName = "",
|
||||
qualityLane?: YoutubeQualityLane,
|
||||
): string {
|
||||
const lane = laneName.trim();
|
||||
const fromQuality = (qualityLane?.source_display || qualityLane?.source_title || "").trim();
|
||||
const source = fromQuality || douyinSourceDisplayFor(row, urlLines).trim();
|
||||
if (source && source !== lane) return source;
|
||||
if (fromQuality) return fromQuality;
|
||||
return douyinSourceDisplayFor(row, urlLines) || laneName.trim();
|
||||
}
|
||||
|
||||
function proLaneDouyinSubtitle(row?: LiveProcRow, urlLines = "", laneName = ""): string {
|
||||
const source = douyinSourceDisplayFor(row, urlLines).trim();
|
||||
const lane = laneName.trim();
|
||||
if (isLivePushingRow(row) && lane && source && lane !== source) return lane;
|
||||
return "";
|
||||
}
|
||||
|
||||
@ -428,12 +413,6 @@ 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");
|
||||
@ -672,7 +651,6 @@ function LiveStreamActionBtn({
|
||||
targetPm2,
|
||||
busy,
|
||||
online,
|
||||
pushing,
|
||||
label,
|
||||
className,
|
||||
baseLock,
|
||||
@ -686,7 +664,6 @@ function LiveStreamActionBtn({
|
||||
targetPm2: string;
|
||||
busy: string | null;
|
||||
online: boolean;
|
||||
pushing: boolean;
|
||||
label: string;
|
||||
className: string;
|
||||
baseLock: boolean;
|
||||
@ -700,8 +677,7 @@ function LiveStreamActionBtn({
|
||||
const actionForBusy = busyKind ?? kind;
|
||||
const loading = !!(forThisProc && pb.action === actionForBusy);
|
||||
const siblingBusy = !!(forThisProc && pb.action !== actionForBusy);
|
||||
// Start locks on pushing OR process online (waiting source still counts as started).
|
||||
const blockStart = kind === "start" && (pushing || online);
|
||||
const blockStart = kind === "start" && online;
|
||||
const blockStop = kind === "stop" && !online;
|
||||
const blockRestart = kind === "restart" && !online;
|
||||
const blocked = blockStart || blockStop || blockRestart;
|
||||
@ -714,11 +690,7 @@ function LiveStreamActionBtn({
|
||||
return;
|
||||
}
|
||||
if (blockStart) {
|
||||
notify(
|
||||
pushing
|
||||
? t("已在推流中,无需重复开始", "Already pushing")
|
||||
: t("进程已在运行,请用「停止」或「重新开始」", "Already running — use Stop or Restart"),
|
||||
);
|
||||
notify(t("已在直播中,无需重复开始", "Already live"));
|
||||
return;
|
||||
}
|
||||
if (blockStop) {
|
||||
@ -803,7 +775,7 @@ export function LiveYoutubeUnmannedView({
|
||||
[liveProcesses, singleProcessOptions],
|
||||
);
|
||||
|
||||
const [mode, setMode] = useState<"single" | "pro">(DEFAULT_YOUTUBE_MODE);
|
||||
const [mode, setMode] = useState<"single" | "pro">("single");
|
||||
const [channels, setChannels] = useState<YoutubeProChannel[]>([]);
|
||||
const [activeCh, setActiveCh] = useState<string>("");
|
||||
const [singleUrlDraft, setSingleUrlDraft] = useState(urlConfig);
|
||||
@ -1038,14 +1010,12 @@ export function LiveYoutubeUnmannedView({
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
if (HIDE_YOUTUBE_MODE_TOGGLE) {
|
||||
setMode(DEFAULT_YOUTUBE_MODE);
|
||||
window.localStorage.setItem(MODE_KEY, DEFAULT_YOUTUBE_MODE);
|
||||
if (HIDE_YOUTUBE_MULTI_PRO_TOGGLE) {
|
||||
setMode("single");
|
||||
return;
|
||||
}
|
||||
const m = window.localStorage.getItem(MODE_KEY);
|
||||
if (m === "pro" || m === "single") setMode(m);
|
||||
else setMode(DEFAULT_YOUTUBE_MODE);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
@ -1057,10 +1027,7 @@ export function LiveYoutubeUnmannedView({
|
||||
try {
|
||||
const remote = await fetchYoutubeProChannelsRemote(fetchJson);
|
||||
if (remote.fetched && remote.channels.length && !cancelled) {
|
||||
const nextChannels = stabilizeYoutubeProChannelOrder(
|
||||
channelsRef.current,
|
||||
cleanYoutubeProChannelNames(remote.channels),
|
||||
);
|
||||
const nextChannels = cleanYoutubeProChannelNames(remote.channels);
|
||||
channelsRef.current = nextChannels;
|
||||
setChannels(nextChannels);
|
||||
setLaneDrafts(laneDraftsFromChannels(nextChannels));
|
||||
@ -1430,10 +1397,7 @@ export function LiveYoutubeUnmannedView({
|
||||
try {
|
||||
const remote = await fetchYoutubeProChannelsRemote(fetchJson);
|
||||
if (!remote.fetched || !remote.channels.length) return;
|
||||
const nextChannels = stabilizeYoutubeProChannelOrder(
|
||||
channelsRef.current,
|
||||
cleanYoutubeProChannelNames(remote.channels),
|
||||
);
|
||||
const nextChannels = cleanYoutubeProChannelNames(remote.channels);
|
||||
channelsRef.current = nextChannels;
|
||||
setChannels(nextChannels);
|
||||
setLaneDrafts(laneDraftsFromChannels(nextChannels));
|
||||
@ -1994,7 +1958,6 @@ 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);
|
||||
@ -2029,7 +1992,6 @@ export function LiveYoutubeUnmannedView({
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (HIDE_YOUTUBE_QUALITY_GUARD) return;
|
||||
void refreshQualityGuard();
|
||||
if (qualityGuardPollIntervalMs <= 0) return;
|
||||
const id = window.setInterval(() => void refreshQualityGuard(), qualityGuardPollIntervalMs);
|
||||
@ -2069,7 +2031,6 @@ export function LiveYoutubeUnmannedView({
|
||||
[statusLogActivity, pageVisible],
|
||||
);
|
||||
const singleOnline = pm2StatusOnline(statusForPm2(singleRuntimeProc));
|
||||
const singlePushing = procStartBlocked(singleRow);
|
||||
const activeSourceDisplay = active
|
||||
? douyinSourceDisplayFor(rowForPm2(resolveChannelPm2(active)), proUrlDraft || active.urlLines || "")
|
||||
: "";
|
||||
@ -2093,8 +2054,7 @@ export function LiveYoutubeUnmannedView({
|
||||
const overviewLaneName = overviewChannel
|
||||
? cleanLaneName(overviewChannel.name, overviewLaneIndex >= 0 ? overviewLaneIndex : 0)
|
||||
: "";
|
||||
const overviewSource =
|
||||
proLanePrimaryTitle(overviewLaneName) || douyinSourceDisplayFor(overviewRow, monitorUrlDraft);
|
||||
const overviewSource = proLanePrimaryTitle(overviewLaneName, overviewRow, monitorUrlDraft);
|
||||
const overviewDouyinSubtitle = proLaneDouyinSubtitle(overviewRow, monitorUrlDraft, overviewLaneName);
|
||||
const overviewStatusLabel = proLaneStatusLabel(overviewRow, t);
|
||||
const overviewSourceUrl = douyinSourceUrlFor(overviewRow, monitorUrlDraft);
|
||||
@ -3064,17 +3024,17 @@ export function LiveYoutubeUnmannedView({
|
||||
</h2>
|
||||
<p className="mt-0.5 text-xs text-zinc-500">
|
||||
{t(
|
||||
"多频道 Pro:每条线路独立保存密钥、URL 列表和 PM2 任务。填好后保存,再点「开始」。Neko 浏览器仅作辅助工作室,不再阻塞推流。",
|
||||
"Multi Pro: each lane keeps its own key, URL list, and PM2 task. Save, then Start. Neko is optional browser tooling and no longer blocks streaming.",
|
||||
"单路一条流;多路时每条线路独立保存自己的密钥、URL 列表和 PM2 任务。填好后保存,再点「开始」。Neko 浏览器仅作辅助工作室,不再阻塞推流。",
|
||||
"Single lane or multi-lane: every lane keeps its own key, URL list, and PM2 task. Save, then Start. Neko is optional browser tooling and no longer blocks streaming.",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={`ml-auto flex shrink-0 self-start rounded-xl border border-white/10 bg-black/30 p-1 ${
|
||||
HIDE_YOUTUBE_MODE_TOGGLE ? "hidden" : ""
|
||||
HIDE_YOUTUBE_MULTI_PRO_TOGGLE ? "hidden" : ""
|
||||
}`}
|
||||
aria-hidden={HIDE_YOUTUBE_MODE_TOGGLE}
|
||||
aria-hidden={HIDE_YOUTUBE_MULTI_PRO_TOGGLE}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@ -3176,13 +3136,12 @@ export function LiveYoutubeUnmannedView({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
|
||||
<div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-3">
|
||||
<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}
|
||||
@ -3195,7 +3154,6 @@ 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}
|
||||
@ -3208,7 +3166,6 @@ 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}
|
||||
@ -3216,15 +3173,6 @@ 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)}`}>
|
||||
@ -3269,13 +3217,12 @@ 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);
|
||||
const laneQuality = qualityGuard?.lanes?.find((lane) => lane.process === pm);
|
||||
const laneDisplay = proLanePrimaryTitle(laneName);
|
||||
const laneDouyinSubtitle = proLaneDouyinSubtitle(row, laneUrlText, laneName, laneQuality);
|
||||
const laneDisplay = proLanePrimaryTitle(laneName, row, laneUrlText, laneQuality);
|
||||
const laneDouyinSubtitle = proLaneDouyinSubtitle(row, laneUrlText, laneName);
|
||||
const laneStatusLabel = proLaneStatusLabel(row, t);
|
||||
const laneLiveMetrics = qualityLaneMetrics(row, laneQuality);
|
||||
const laneStatsText = formatFfmpegStatsBrief(laneLiveMetrics, {
|
||||
@ -3382,7 +3329,6 @@ 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}
|
||||
@ -3396,7 +3342,6 @@ 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}
|
||||
@ -3410,7 +3355,6 @@ 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}
|
||||
@ -3419,15 +3363,6 @@ 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"
|
||||
@ -3455,21 +3390,18 @@ export function LiveYoutubeUnmannedView({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!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}
|
||||
<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_QUALITY_GUARD ? qualityGuardPanel : null}
|
||||
|
||||
|
||||
@ -43,30 +43,6 @@ export function cleanYoutubeProChannelNames(channels: YoutubeProChannel[]): Yout
|
||||
}));
|
||||
}
|
||||
|
||||
/** Keep previous card order when applying a remote channel list. */
|
||||
export function stabilizeYoutubeProChannelOrder(
|
||||
previous: YoutubeProChannel[],
|
||||
incoming: YoutubeProChannel[],
|
||||
): YoutubeProChannel[] {
|
||||
if (!previous.length || !incoming.length) return incoming;
|
||||
const byId = new Map(incoming.map((row) => [row.id, row]));
|
||||
const byPm2 = new Map(incoming.map((row) => [resolveYoutubeProChannelPm2(row), row]));
|
||||
const out: YoutubeProChannel[] = [];
|
||||
const used = new Set<string>();
|
||||
for (const prev of previous) {
|
||||
const hit = byId.get(prev.id) || byPm2.get(resolveYoutubeProChannelPm2(prev));
|
||||
if (!hit || used.has(hit.id)) continue;
|
||||
out.push(hit);
|
||||
used.add(hit.id);
|
||||
}
|
||||
for (const row of incoming) {
|
||||
if (used.has(row.id)) continue;
|
||||
out.push(row);
|
||||
used.add(row.id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function sanitizeYoutubePm2Name(value: string): string {
|
||||
return (value || "").trim().replace(PM2_SANITIZE_RE, "_");
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user