This commit is contained in:
eric 2026-06-03 10:53:02 -05:00
parent bedd74d542
commit 9068257044
94 changed files with 8041 additions and 532 deletions

217
d2ypp2/.gitignore vendored
View File

@ -1,22 +1,16 @@
# Byte-compiled / optimized / DLL files
# Python caches and build output
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
# dist/
downloads/
dist/
eggs/
.eggs/
# 仅忽略仓库根目录的 lib(勿用 lib/ 否则会误伤 scripts/linux/lib)
/lib/
/lib64/
lib/
lib64/
parts/
sdist/
var/
@ -27,168 +21,97 @@ share/python-wheels/
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
# Python tooling
.pytest_cache/
.mypy_cache/
.ruff_cache/
.pyre/
.pytype/
.hypothesis/
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# DouyinLiveRecord
backup_config/
logs/
node/
node-v*.zip
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
# Virtual environments and local env files
.env
.venv
env/
.env.*
!.env.example
.venv/
venv/
env/
ENV/
env.bak/
venv.bak/
__pypackages__/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
backup_config/
# 根目录 npm(concurrently 等)
# Node / Next.js
node_modules/
# Next 开发缓存(静态导出目录 web-console/out 可纳入版本库以便无 Node 环境直接部署)
web-console/node_modules/
web-console/.next/
web-console/.turbo/
web-console/.vercel/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# scrcpy-server:由服务启动或 Docker 构建从 Genymobile Release 自动拉取(可纳入制品库而不提交)
vendor/scrcpy-server.jar
# Paramiko 部署本地日志(可能含敏感命令回显)
# Local runtime state
logs/
downloads/
backup_config/
.deploy_logs/
# 无 PM2 时的本地进程状态
.process_runner/
# 本地排障/运行时生成物
.pm2/
tmp/
services/neko/docker-compose.generated.yml
temp/
*.log
*.pid
*.sock
# 本机端口/主机覆盖(从 config/runtime.env.example 复制)
# Local config and generated state
config/runtime.env
config/system-stack.env
config/hardware.env
config/hardware-profile.json
config/hub_state.sqlite
config/*.sqlite
config/*.sqlite3
config/*.db
# Neko / browser runtime data
services/neko/data/
services/neko/docker-compose.generated.yml
services/neko/no-managed-policies/
services/neko/**/*.log
vendor/scrcpy-server.jar
# Deployment and generated archives
*.zip
*.zip.b64
*.tar
*.tar.gz
*.tgz
*.7z
# OS and editor files
.DS_Store
Thumbs.db
desktop.ini
.idea/
.vscode/
*.swp
*.swo
# Jupyter / notebooks
.ipynb_checkpoints/
# Project-local scratch files
cursor/
cursor*.md
*.tmp

Binary file not shown.

View File

@ -31,6 +31,16 @@ SRS_WEBRTC_UDP_PORT=8000
# ShellCrash
SHELLCRASH_DIR=/etc/ShellCrash
SHELLCRASH_AUTOSTART=0
SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL=1
SHELLCRASH_MANUAL_ONLY=1
SHELLCRASH_AUTO_START_ON_WEB_PANEL=0
SHELLCRASH_ATTACH_WHEN_DIRECT_OK=0
SHELLCRASH_ATTACH_NEKO=auto
SHELLCRASH_ATTACH_FFMPEG=auto
NETWORK_PROBE_GOOGLE_URL=https://www.google.com/generate_204
NETWORK_PROBE_YOUTUBE_URL=https://www.youtube.com/generate_204
NETWORK_PROBE_DOUYIN_URL=https://live.douyin.com/
# Browser / Android lab
BROWSER_PROFILE_DIR=/var/lib/live-browser/profile
@ -100,6 +110,8 @@ NEKO_EXTERNAL_EXTENSIONS=0
NEKO_MANAGED_POLICIES=1
# 启动时重建 Tampermonkey 插件与脚本种子,修复 profile 中损坏/异常的油猴扩展。
NEKO_TAMPERMONKEY_REPAIR=1
# YouTube Studio 页面实时采集 Chrome 扩展:抓取在线人数、直播状态、健康提示、弹窗内容并写入控制台事件库。
NEKO_LIVE_OPS_EXTENSION=1
NEKO_WEBRTC_EPR=52000-52099
NEKO_WEBRTC_EPR_1=52000-52099
NEKO_WEBRTC_EPR_2=52101-52199
@ -117,12 +129,12 @@ NEKO_WEBRTC_UDPMUX=52300
NEKO_WEBRTC_UDPMUX_1=52300
NEKO_WEBRTC_UDPMUX_2=52301
NEKO_WEBRTC_UDPMUX_3=52302
NEKO_ACCESS_MODE=lan
NEKO_WEBRTC_NAT1TO1=
# WireGuard/EasyTier/Tailscale 等覆盖网络地址可显式填入 NEKO_WEBRTC_NAT1TO1(例如 10.88.0.2)。
# 留空时自动选择物理 LAN IP;显式填入本机覆盖网络 IP 时不会被 LAN watcher 覆盖。
# NEKO_ACCESS_MODE=lan 使用物理局域网 IP;NEKO_ACCESS_MODE=remote 且 WireGuard 已启动成功时,控制台会把 Neko NAT1TO1 切到 WireGuard 地址。
NEKO_WIREGUARD_HOST=
NEKO_PUBLIC_HOST=
# 后台 watcher 会定期核对当前 LAN/显式 NAT1TO1;若板子切换 Wi‑Fi / DHCP 后 IP 变化,会自动重启 Neko 刷新 WebRTC NAT 地址
# 后台 watcher 会定期核对当前访问模式的 NAT1TO1;漂移时只重配 Neko 容器,不改 profile/data。
NEKO_IP_WATCH_INTERVAL=15
NEKO_PLUGINS_ENABLED=true
@ -192,5 +204,41 @@ OPENCLAW_GATEWAY_TOKEN=12345678
OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1
OPENCLAW_CONFIG_DIR=/var/lib/live-openclaw/config
OPENCLAW_WORKSPACE_DIR=/var/lib/live-openclaw/workspace
# Studio modules
ENABLE_HOMEASSISTANT=1
HOMEASSISTANT_AUTOSTART=1
HOMEASSISTANT_IMAGE=ghcr.io/home-assistant/home-assistant:stable
HOMEASSISTANT_PORT=8123
HOMEASSISTANT_CONFIG_DIR=/var/lib/live-homeassistant/config
ENABLE_FRIGATE=1
FRIGATE_USB_AUTOSTART=1
FRIGATE_USB_SCAN_INTERVAL=60
FRIGATE_IMAGE=ghcr.io/blakeblackshear/frigate:stable
FRIGATE_WEB_PORT=5001
FRIGATE_RTSP_PORT=8554
FRIGATE_WEBRTC_PORT=8555
FRIGATE_SHM_SIZE=256mb
FRIGATE_CONFIG_DIR=/var/lib/live-frigate/config
FRIGATE_MEDIA_DIR=/var/lib/live-frigate/media
FRIGATE_PRIVILEGED=true
ENABLE_WOL=1
WOL_BROADCAST=255.255.255.255
WOL_PORT=9
WOL_PROBE_INTERVAL=30
WOL_PROBE_CIDR=
ENABLE_NTFY=1
NTFY_IMAGE=binwiederhier/ntfy:latest
NTFY_PORT=8089
NTFY_CONFIG_DIR=/var/lib/live-ntfy/config
NTFY_CACHE_DIR=/var/lib/live-ntfy/cache
ENABLE_COTURN=0
COTURN_IMAGE=coturn/coturn:latest
COTURN_PORT=3478
COTURN_TLS_PORT=5349
COTURN_MIN_PORT=49160
COTURN_MAX_PORT=49200
COTURN_REALM=live.local
COTURN_STATIC_AUTH_SECRET=
# Business profile defaults
ENABLE_SRS=1

Binary file not shown.

View File

@ -178,7 +178,7 @@ def _load_youtube_push_settings(config_file: str) -> dict[str, str | bool]:
"maxrate": "4500k",
"bufsize": "8000k",
"stream_key": "",
"fast_audio": False,
"fast_audio": True,
}
if not os.path.exists(config_file):
return settings
@ -487,7 +487,7 @@ def start_douyin_youtube_ffplay(
stream_key = None
push_proxy = ""
push_proxy_mode = ""
fast_audio = False # 默认恢复强化音频链,必要时可在配置里开启轻量模式
fast_audio = True # 默认使用轻量音频链,优先保证 YouTube ingest speed >= 1.00x
if os.path.exists(config_file):
config = configparser.ConfigParser()

View File

@ -16,7 +16,8 @@
"remote_access": {
"neko": {
"lan": true,
"wireguard": true,
"wireguard": "switch",
"mode_env": "NEKO_ACCESS_MODE",
"nat1to1_env": "NEKO_WEBRTC_NAT1TO1",
"wireguard_host_env": "NEKO_WIREGUARD_HOST"
}

View File

@ -0,0 +1,10 @@
{
"enabled": false,
"image": "coturn/coturn:latest",
"port": 3478,
"tls_port": 5349,
"min_port": 49160,
"max_port": 49200,
"realm": "live.local",
"static_auth_secret": ""
}

View File

@ -0,0 +1,13 @@
{
"id": "frigate",
"layer": "studio",
"enabled": true,
"manager": "docker",
"ports": { "http": 5001, "rtsp": 8554, "webrtc": 8555 },
"env": {
"ENABLE_FRIGATE": "1",
"FRIGATE_WEB_PORT": "5001",
"FRIGATE_CONFIG_DIR": "/var/lib/live-frigate/config",
"FRIGATE_MEDIA_DIR": "/var/lib/live-frigate/media"
}
}

View File

@ -0,0 +1,12 @@
{
"id": "homeassistant",
"layer": "studio",
"enabled": true,
"manager": "docker",
"ports": { "http": 8123 },
"env": {
"ENABLE_HOMEASSISTANT": "1",
"HOMEASSISTANT_PORT": "8123",
"HOMEASSISTANT_CONFIG_DIR": "/var/lib/live-homeassistant/config"
}
}

View File

@ -28,6 +28,8 @@
"NEKO_WEBRTC_UDPMUX": "52300",
"NEKO_WEBRTC_UDPMUX_1": "52300",
"NEKO_WEBRTC_UDPMUX_2": "52301",
"NEKO_WEBRTC_UDPMUX_3": "52302"
"NEKO_WEBRTC_UDPMUX_3": "52302",
"NEKO_ACCESS_MODE": "lan",
"NEKO_WIREGUARD_HOST": ""
}
}

View File

@ -0,0 +1,13 @@
{
"id": "ntfy",
"layer": "studio",
"enabled": true,
"manager": "docker",
"ports": { "http": 8089 },
"env": {
"ENABLE_NTFY": "1",
"NTFY_PORT": "8089",
"NTFY_CONFIG_DIR": "/var/lib/live-ntfy/config",
"NTFY_CACHE_DIR": "/var/lib/live-ntfy/cache"
}
}

View File

@ -0,0 +1,12 @@
{
"id": "wol",
"layer": "studio",
"enabled": true,
"manager": "builtin",
"ports": {},
"env": {
"ENABLE_WOL": "1",
"WOL_BROADCAST": "255.255.255.255",
"WOL_PORT": "9"
}
}

View File

@ -139,7 +139,7 @@ def _pick_node_runtime(min_major: int = MIN_WEB_NODE_MAJOR) -> NodeRuntime | Non
major = _node_version_major(node)
if major is None:
continue
npm = node.with_name("npm")
npm = node.with_name("npm.cmd" if os.name == "nt" else "npm")
if not npm.exists():
npm = shutil.which("npm", path=str(node.parent))
npm = Path(npm) if npm else None
@ -157,7 +157,7 @@ def _runtime_env(runtime: NodeRuntime, extra: dict[str, str] | None = None) -> d
node_dir = str(runtime.node.parent)
env["PATH"] = f"{node_dir}{os.pathsep}{path}" if path else node_dir
env.setdefault("NEXT_TELEMETRY_DISABLED", "1")
if runtime.npm is not None:
if runtime.npm is not None and os.name != "nt":
env["npm_config_script_shell"] = env.get("npm_config_script_shell", "/bin/sh")
if extra:
env.update(extra)
@ -255,6 +255,8 @@ def _docker_available() -> str | None:
def _run_console_cmd(cmd: list[str], *, cwd: Path, env: dict[str, str]) -> int:
if os.name == "nt" and cmd and Path(str(cmd[0])).suffix.lower() in {".cmd", ".bat"}:
cmd = ["cmd.exe", "/c", *cmd]
return subprocess.call(cmd, cwd=cwd, env=env)

View File

@ -0,0 +1,22 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="${ROOT_DIR:-$(cd "$(dirname "$0")/../.." && pwd)}"
SERVICE_CTL="$ROOT_DIR/scripts/linux/service_ctl.sh"
CONFIG_DIR="$ROOT_DIR/config"
STACK_ENV="$CONFIG_DIR/system-stack.env"
[ -f "$STACK_ENV" ] && set -a && . "$STACK_ENV" && set +a
interval="${FRIGATE_USB_SCAN_INTERVAL:-60}"
case "$interval" in
''|*[!0-9]*) interval=60 ;;
esac
[ "$interval" -lt 10 ] 2>/dev/null && interval=10
while true; do
if [ -x "$SERVICE_CTL" ] || [ -f "$SERVICE_CTL" ]; then
bash "$SERVICE_CTL" frigate auto >/dev/null 2>&1 || true
fi
sleep "$interval"
done

View File

@ -32,6 +32,10 @@ prepare_mitmproxy
prepare_vscode_server
prepare_uptime_kuma
prepare_openclaw
prepare_homeassistant
prepare_frigate
prepare_ntfy
prepare_coturn
install_pulseaudio_service
install_kmscube_service
install_webtty

View File

@ -36,6 +36,10 @@ prepare_mitmproxy
prepare_vscode_server
prepare_uptime_kuma
prepare_openclaw
prepare_homeassistant
prepare_frigate
prepare_ntfy
prepare_coturn
install_pulseaudio_service
install_kmscube_service
prepare_srs

View File

@ -35,6 +35,10 @@ prepare_mitmproxy
prepare_vscode_server
prepare_uptime_kuma
prepare_openclaw
prepare_homeassistant
prepare_frigate
prepare_ntfy
prepare_coturn
install_pulseaudio_service
install_kmscube_service
install_webtty

View File

@ -138,6 +138,13 @@ have() {
command -v "$1" >/dev/null 2>&1
}
flag_enabled() {
case "${1:-}" in
1|true|TRUE|yes|YES|on|ON|enable|enabled) return 0 ;;
*) return 1 ;;
esac
}
need_docker() {
[ "${ENABLE_SRS:-1}" = "1" ] || \
[ "${ENABLE_HOMEPAGE:-1}" = "1" ] || \
@ -147,7 +154,11 @@ need_docker() {
[ "${ENABLE_MITMPROXY:-1}" = "1" ] || \
[ "${ENABLE_VSCODE_SERVER:-1}" = "1" ] || \
[ "${ENABLE_UPTIME_KUMA:-1}" = "1" ] || \
[ "${ENABLE_OPENCLAW:-1}" = "1" ]
[ "${ENABLE_OPENCLAW:-1}" = "1" ] || \
[ "${ENABLE_HOMEASSISTANT:-1}" = "1" ] || \
[ "${ENABLE_FRIGATE:-1}" = "1" ] || \
[ "${ENABLE_NTFY:-1}" = "1" ] || \
[ "${ENABLE_COTURN:-0}" = "1" ]
}
compose_run() {
@ -270,6 +281,16 @@ load_env() {
SRS_SRT_PORT="${SRS_SRT_PORT:-10080}"
SRS_WEBRTC_PORT="${SRS_WEBRTC_PORT:-8088}"
SHELLCRASH_DIR="${SHELLCRASH_DIR:-/etc/ShellCrash}"
SHELLCRASH_AUTOSTART="${SHELLCRASH_AUTOSTART:-0}"
SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL="${SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL:-1}"
SHELLCRASH_MANUAL_ONLY="${SHELLCRASH_MANUAL_ONLY:-1}"
SHELLCRASH_AUTO_START_ON_WEB_PANEL="${SHELLCRASH_AUTO_START_ON_WEB_PANEL:-0}"
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}"
NETWORK_PROBE_GOOGLE_URL="${NETWORK_PROBE_GOOGLE_URL:-https://www.google.com/generate_204}"
NETWORK_PROBE_YOUTUBE_URL="${NETWORK_PROBE_YOUTUBE_URL:-https://www.youtube.com/generate_204}"
NETWORK_PROBE_DOUYIN_URL="${NETWORK_PROBE_DOUYIN_URL:-https://live.douyin.com/}"
WEBTTY_USER="${WEBTTY_USER:-live}"
WEBTTY_PASS="${WEBTTY_PASS:-12345678}"
FILEBROWSER_USER="${FILEBROWSER_USER:-live}"
@ -313,6 +334,7 @@ load_env() {
NEKO_WEBRTC_EPR_1="${NEKO_WEBRTC_EPR_1:-$NEKO_WEBRTC_EPR}"
NEKO_WEBRTC_EPR_2="${NEKO_WEBRTC_EPR_2:-$NEKO_WEBRTC_UDP_RANGE_2}"
NEKO_WEBRTC_EPR_3="${NEKO_WEBRTC_EPR_3:-$NEKO_WEBRTC_UDP_RANGE_3}"
NEKO_ACCESS_MODE="${NEKO_ACCESS_MODE:-lan}"
NEKO_IMAGE_X86="${NEKO_IMAGE_X86:-ghcr.io/m1k1o/neko/google-chrome:3.0.0}"
NEKO_IMAGE_ARM64="${NEKO_IMAGE_ARM64:-ghcr.io/m1k1o/neko/chromium:3.0.0}"
case "$NEKO_IMAGE_X86" in
@ -378,6 +400,40 @@ load_env() {
OPENCLAW_ALLOW_INSECURE_PRIVATE_WS="${OPENCLAW_ALLOW_INSECURE_PRIVATE_WS:-1}"
OPENCLAW_CONFIG_DIR="${OPENCLAW_CONFIG_DIR:-/var/lib/live-openclaw/config}"
OPENCLAW_WORKSPACE_DIR="${OPENCLAW_WORKSPACE_DIR:-/var/lib/live-openclaw/workspace}"
ENABLE_HOMEASSISTANT="${ENABLE_HOMEASSISTANT:-1}"
HOMEASSISTANT_AUTOSTART="${HOMEASSISTANT_AUTOSTART:-1}"
HOMEASSISTANT_IMAGE="${HOMEASSISTANT_IMAGE:-ghcr.io/home-assistant/home-assistant:stable}"
HOMEASSISTANT_PORT="${HOMEASSISTANT_PORT:-8123}"
HOMEASSISTANT_CONFIG_DIR="${HOMEASSISTANT_CONFIG_DIR:-/var/lib/live-homeassistant/config}"
ENABLE_FRIGATE="${ENABLE_FRIGATE:-1}"
FRIGATE_USB_AUTOSTART="${FRIGATE_USB_AUTOSTART:-1}"
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}"
FRIGATE_RTSP_PORT="${FRIGATE_RTSP_PORT:-8554}"
FRIGATE_WEBRTC_PORT="${FRIGATE_WEBRTC_PORT:-8555}"
FRIGATE_SHM_SIZE="${FRIGATE_SHM_SIZE:-256mb}"
FRIGATE_CONFIG_DIR="${FRIGATE_CONFIG_DIR:-/var/lib/live-frigate/config}"
FRIGATE_MEDIA_DIR="${FRIGATE_MEDIA_DIR:-/var/lib/live-frigate/media}"
FRIGATE_PRIVILEGED="${FRIGATE_PRIVILEGED:-true}"
ENABLE_WOL="${ENABLE_WOL:-1}"
WOL_BROADCAST="${WOL_BROADCAST:-255.255.255.255}"
WOL_PORT="${WOL_PORT:-9}"
WOL_PROBE_INTERVAL="${WOL_PROBE_INTERVAL:-30}"
WOL_PROBE_CIDR="${WOL_PROBE_CIDR:-}"
ENABLE_NTFY="${ENABLE_NTFY:-1}"
NTFY_IMAGE="${NTFY_IMAGE:-binwiederhier/ntfy:latest}"
NTFY_PORT="${NTFY_PORT:-8089}"
NTFY_CONFIG_DIR="${NTFY_CONFIG_DIR:-/var/lib/live-ntfy/config}"
NTFY_CACHE_DIR="${NTFY_CACHE_DIR:-/var/lib/live-ntfy/cache}"
ENABLE_COTURN="${ENABLE_COTURN:-0}"
COTURN_IMAGE="${COTURN_IMAGE:-coturn/coturn:latest}"
COTURN_PORT="${COTURN_PORT:-3478}"
COTURN_TLS_PORT="${COTURN_TLS_PORT:-5349}"
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:-}"
}
resolve_neko_image() {
@ -857,6 +913,26 @@ ensure_live_user() {
fi
}
ensure_live_can_traverse_repo_root() {
local dir parent
id -u live >/dev/null 2>&1 || return 0
[ -d "$ROOT_DIR" ] || return 0
chmod a+rx "$ROOT_DIR" 2>/dev/null || true
parent="$(dirname "$ROOT_DIR")"
while [ -n "$parent" ] && [ "$parent" != "/" ]; do
if runuser -u live -- test -x "$parent" 2>/dev/null; then
:
elif have setfacl; then
setfacl -m u:live:--x "$parent" 2>/dev/null || chmod o+x "$parent" 2>/dev/null || true
else
chmod o+x "$parent" 2>/dev/null || true
fi
dir="$parent"
parent="$(dirname "$dir")"
done
}
normalize_repo_root() {
local parent safe_root
parent="$(dirname "$ROOT_DIR")"
@ -905,6 +981,25 @@ ensure_neko_data_permissions() {
chmod -R a+rwX "$data_dir" 2>/dev/null || true
}
ensure_project_full_access() {
[ -d "$ROOT_DIR" ] || return 0
chmod -R a+rwX "$ROOT_DIR" 2>/dev/null || true
find "$ROOT_DIR" -type d -exec chmod a+rwx {} \; 2>/dev/null || true
for path in \
"${HOMEASSISTANT_CONFIG_DIR:-}" \
"${FRIGATE_CONFIG_DIR:-}" \
"${FRIGATE_MEDIA_DIR:-}" \
"${NTFY_CONFIG_DIR:-}" \
"${NTFY_CACHE_DIR:-}" \
"${OPENCLAW_CONFIG_DIR:-}" \
"${OPENCLAW_WORKSPACE_DIR:-}"
do
[ -n "${path:-}" ] || continue
mkdir -p "$path" 2>/dev/null || true
chmod -R a+rwX "$path" 2>/dev/null || true
done
}
ensure_runtime_dirs_owned_by_live() {
local rel path
for rel in \
@ -923,13 +1018,14 @@ ensure_runtime_dirs_owned_by_live() {
path="$ROOT_DIR/$rel"
mkdir -p "$path"
chown -R live:live "$path" 2>/dev/null || true
chmod -R u+rwX,g+rwX "$path" 2>/dev/null || true
chmod -R a+rwX "$path" 2>/dev/null || true
done
mkdir -p "$ROOT_DIR/services/neko"
chown live:live "$ROOT_DIR/services" "$ROOT_DIR/services/neko" 2>/dev/null || true
find "$ROOT_DIR/services/neko" -mindepth 1 -maxdepth 1 ! -name data -exec chown -R live:live {} + 2>/dev/null || true
find "$ROOT_DIR/services/neko" -mindepth 1 -maxdepth 1 ! -name data -exec chmod -R u+rwX,g+rwX {} + 2>/dev/null || true
find "$ROOT_DIR/services/neko" -mindepth 1 -maxdepth 1 ! -name data -exec chmod -R a+rwX {} + 2>/dev/null || true
ensure_neko_data_permissions
ensure_project_full_access
}
configure_host_dns() {
@ -1162,7 +1258,9 @@ install_live_console_service() {
local neko_profile_owner
neko_profile_owner="${NEKO_CONTAINER_UID:-1000}:${NEKO_CONTAINER_GID:-1000}"
log "Installing live console service"
ensure_live_can_traverse_repo_root
chmod +x "$ROOT_DIR/start.sh" "$ROOT_DIR/web.sh" "$ROOT_DIR/dev.sh" "$SERVICE_CTL" "$WEBTTY_SHELL"
systemctl unmask live-console.service >/dev/null 2>&1 || true
cat >/etc/systemd/system/live-console.service <<UNIT
[Unit]
Description=Live Super Hub Control Plane
@ -1172,11 +1270,8 @@ Wants=network-online.target
StartLimitIntervalSec=0
[Service]
User=live
Group=live
PermissionsStartOnly=true
AmbientCapabilities=CAP_NET_ADMIN
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW
User=root
Group=root
UMask=0000
WorkingDirectory=$ROOT_DIR
Environment=HOST=0.0.0.0
@ -1188,6 +1283,7 @@ ExecStartPre=/bin/chown -R live:live $ROOT_DIR/config $ROOT_DIR/logs $ROOT_DIR/d
ExecStartPre=/bin/bash -lc 'mkdir -p "$ROOT_DIR/services/neko/data"; chown live:live "$ROOT_DIR/services" "$ROOT_DIR/services/neko" 2>/dev/null || true; find "$ROOT_DIR/services/neko" -mindepth 1 -maxdepth 1 ! -name data -exec chown -R live:live {} + 2>/dev/null || true; chown -R $neko_profile_owner "$ROOT_DIR/services/neko/data" 2>/dev/null || true; chmod -R a+rwX "$ROOT_DIR/services/neko/data" 2>/dev/null || true'
ExecStartPre=/bin/chown -R root:root $ROOT_DIR
ExecStartPre=/bin/chmod -R 0777 $ROOT_DIR
ExecStartPre=/bin/bash -lc 'for p in "${HOMEASSISTANT_CONFIG_DIR:-/var/lib/live-homeassistant/config}" "${FRIGATE_CONFIG_DIR:-/var/lib/live-frigate/config}" "${FRIGATE_MEDIA_DIR:-/var/lib/live-frigate/media}" "${NTFY_CONFIG_DIR:-/var/lib/live-ntfy/config}" "${NTFY_CACHE_DIR:-/var/lib/live-ntfy/cache}"; do mkdir -p "\$p"; chmod -R a+rwX "\$p" 2>/dev/null || true; done'
ExecStart=$ROOT_DIR/start.sh
Restart=always
RestartSec=5
@ -1288,17 +1384,29 @@ detect_mdns_interfaces() {
fi
}
detect_preferred_lan_ip() {
local src iface candidate path name
is_physical_lan_iface_name() {
local name="${1:-}"
case "$name" in
""|lo|docker*|br-*|veth*|virbr*|tun*|tap*|zt*|tailscale*|wg*|wireguard*|sit*|dummy*|p2p-dev-*|mon.*)
return 1
;;
esac
return 0
}
src="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for (i=1; i<=NF; i++) if ($i=="src") {print $(i+1); exit}}')"
if [ -n "$src" ]; then
detect_preferred_lan_ip() {
local route src iface candidate path name
route="$(ip -4 route get 1.1.1.1 2>/dev/null || true)"
src="$(printf '%s\n' "$route" | awk '{for (i=1; i<=NF; i++) if ($i=="src") {print $(i+1); exit}}')"
iface="$(printf '%s\n' "$route" | awk '{for (i=1; i<=NF; i++) if ($i=="dev") {print $(i+1); exit}}')"
if [ -n "$src" ] && is_physical_lan_iface_name "$iface"; then
printf '%s\n' "$src"
return 0
fi
iface="$(ip route show default 2>/dev/null | awk 'NR==1 {print $5}')"
if [ -n "$iface" ]; then
if is_physical_lan_iface_name "$iface"; then
src="$(ip -4 addr show dev "$iface" 2>/dev/null | awk '$1=="inet" {sub(/\/.*/, "", $2); print $2; exit}')"
if [ -n "$src" ]; then
printf '%s\n' "$src"
@ -1309,11 +1417,7 @@ detect_preferred_lan_ip() {
for path in /sys/class/net/*; do
[ -e "$path" ] || continue
name="${path##*/}"
case "$name" in
lo|docker*|br-*|veth*|virbr*|tun*|tap*|zt*|tailscale*|wg*|sit*|dummy*|p2p-dev-*|mon.*)
continue
;;
esac
is_physical_lan_iface_name "$name" || continue
candidate="$(ip -4 addr show dev "$name" 2>/dev/null | awk '$1=="inet" {sub(/\/.*/, "", $2); print $2; exit}')"
if [ -n "$candidate" ]; then
printf '%s\n' "$candidate"
@ -1347,8 +1451,8 @@ neko_nat1to1_is_usable() {
return 1
;;
*)
# Explicit NAT1TO1 may intentionally be a WireGuard/Tailscale/EasyTier address.
# Auto-detection still prefers physical LAN via detect_preferred_lan_ip().
# Explicit NAT1TO1 may be a physical LAN or WireGuard address, but auto-detection
# stays on the physical LAN path via detect_preferred_lan_ip().
return 0
;;
esac
@ -1562,10 +1666,75 @@ shellcrash_mix_port() {
printf '%s' "$port"
}
shellcrash_config_available() {
[ -s "$SHELLCRASH_DIR/yamls/config.yaml" ] || [ -s "/tmp/ShellCrash/config.yaml" ]
}
system_probe_url() {
local url="$1"
[ -n "$url" ] || return 1
if have curl; then
curl -kfsSL --connect-timeout 3 --max-time 5 --noproxy '*' -o /dev/null "$url" 2>/dev/null && return 0
elif have wget; then
env -u http_proxy -u https_proxy -u HTTP_PROXY -u HTTPS_PROXY -u all_proxy -u ALL_PROXY \
wget -q --no-check-certificate --timeout=5 -O /dev/null "$url" 2>/dev/null && return 0
fi
return 1
}
system_direct_global_ready() {
flag_enabled "${SHELLCRASH_FORCE_PROXY:-0}" && return 1
system_probe_url "$NETWORK_PROBE_GOOGLE_URL" && return 0
system_probe_url "$NETWORK_PROBE_YOUTUBE_URL" && return 0
return 1
}
shellcrash_should_autostart_on_direct_fail() {
flag_enabled "$SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL" || return 1
system_direct_global_ready && return 1
shellcrash_config_available
}
shellcrash_set_systemd_autostart_for_policy() {
if shellcrash_should_autostart_on_direct_fail; then
systemctl enable shellcrash.service >/dev/null 2>&1 || true
else
systemctl disable shellcrash.service >/dev/null 2>&1 || true
fi
}
shellcrash_autostart_if_needed() {
shellcrash_should_autostart_on_direct_fail || return 1
shellcrash_sync_runtime_config >/dev/null 2>&1 || return 1
if systemctl list-unit-files shellcrash.service --no-legend 2>/dev/null | grep -q '^shellcrash.service'; then
systemctl reset-failed shellcrash.service >/dev/null 2>&1 || true
systemctl enable --now shellcrash.service >/dev/null 2>&1 || return 1
elif [ -x "$SHELLCRASH_DIR/start.sh" ]; then
"$SHELLCRASH_DIR/start.sh" start >/dev/null 2>&1 || return 1
else
return 1
fi
}
neko_default_proxy_bypass() {
printf '%s' '<-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'
}
shellcrash_proxy_available() {
local port="$1"
[ "${ENABLE_SHELLCRASH:-1}" = "1" ] || return 1
if systemctl list-unit-files shellcrash.service --no-legend >/dev/null 2>&1 && ! systemctl is-active --quiet shellcrash.service; then
return 1
fi
if have ss; then
ss -ltn 2>/dev/null | awk -v p=":$port" '
$4 ~ p"$" && $4 !~ /(^|:)127\.0\.0\.1:/ && $4 !~ /\[::1\]:/ { found=1 }
END { exit(found ? 0 : 1) }
' && return 0
fi
return 1
}
resolve_neko_browser_proxy() {
case "${NEKO_BROWSER_PROXY:-}" in
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
@ -1577,8 +1746,20 @@ resolve_neko_browser_proxy() {
return 0
;;
esac
[ "${ENABLE_SHELLCRASH:-1}" = "1" ] || return 0
printf 'http://host.docker.internal:%s' "$(shellcrash_mix_port)"
case "$SHELLCRASH_ATTACH_NEKO" in
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
return 0
;;
esac
if ! flag_enabled "$SHELLCRASH_ATTACH_WHEN_DIRECT_OK" && system_direct_global_ready; then
return 0
fi
shellcrash_autostart_if_needed >/dev/null 2>&1 || true
local port
port="$(shellcrash_mix_port)"
if shellcrash_proxy_available "$port"; then
printf 'http://host.docker.internal:%s' "$port"
fi
}
ensure_neko_browser_launcher_executable() {
@ -1666,6 +1847,20 @@ EOF
fi
fi
fi
if systemctl list-unit-files shellcrash.service --no-legend 2>/dev/null | grep -q '^shellcrash.service'; then
if shellcrash_should_autostart_on_direct_fail; then
systemctl reset-failed shellcrash.service >/dev/null 2>&1 || true
systemctl enable --now shellcrash.service >/dev/null 2>&1 || true
else
systemctl disable --now shellcrash.service >/dev/null 2>&1 || systemctl stop shellcrash.service >/dev/null 2>&1 || true
fi
elif [ -x "$SHELLCRASH_DIR/start.sh" ]; then
if shellcrash_should_autostart_on_direct_fail; then
"$SHELLCRASH_DIR/start.sh" start >/dev/null 2>&1 || true
else
"$SHELLCRASH_DIR/start.sh" stop >/dev/null 2>&1 || true
fi
fi
shellcrash_sync_runtime_config || log "WARN: ShellCrash config.yaml is not staged yet; apply a YAML profile before starting"
grant_shellcrash_web_write_access
}
@ -1802,6 +1997,7 @@ install_neko_browser() {
export NEKO_WEBRTC_EPR_1="${NEKO_WEBRTC_EPR_1:-$NEKO_WEBRTC_EPR}"
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}"
# 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
@ -1817,11 +2013,7 @@ install_neko_browser() {
export NEKO_WEBRTC_UDPMUX_1="${NEKO_WEBRTC_UDPMUX_1:-$NEKO_WEBRTC_UDPMUX}"
export NEKO_WEBRTC_UDPMUX_2="${NEKO_WEBRTC_UDPMUX_2:-52301}"
export NEKO_WEBRTC_UDPMUX_3="${NEKO_WEBRTC_UDPMUX_3:-52302}"
if neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then
export NEKO_WEBRTC_NAT1TO1
elif neko_nat1to1_is_usable "${NEKO_WIREGUARD_HOST:-}"; then
export NEKO_WEBRTC_NAT1TO1="$NEKO_WIREGUARD_HOST"
else
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}"
@ -2274,6 +2466,34 @@ YAML
- OpenClaw:
href: http://${HOSTNAME_ALIAS}.local:${OPENCLAW_GATEWAY_PORT}
description: Multi-agent automation gateway and web workspace
YAML
fi
if [ "${ENABLE_HOMEASSISTANT:-1}" = "1" ]; then
cat >>"$target" <<YAML
- Home Assistant:
href: http://${HOSTNAME_ALIAS}.local:${HOMEASSISTANT_PORT}
description: Local automation workspace
YAML
fi
if [ "${ENABLE_FRIGATE:-1}" = "1" ]; then
cat >>"$target" <<YAML
- Frigate NVR:
href: http://${HOSTNAME_ALIAS}.local:${FRIGATE_WEB_PORT}
description: Camera NVR and detection console
YAML
fi
if [ "${ENABLE_NTFY:-1}" = "1" ]; then
cat >>"$target" <<YAML
- ntfy:
href: http://${HOSTNAME_ALIAS}.local:${NTFY_PORT}
description: LAN notification topic server
YAML
fi
if [ "${ENABLE_WOL:-1}" = "1" ]; then
cat >>"$target" <<YAML
- WOL Network Wake:
href: http://${HOSTNAME_ALIAS}.local:${PORT}/?view=studio
description: Wake-on-LAN sender in Studio
YAML
fi
}
@ -2454,6 +2674,107 @@ prepare_openclaw() {
log "WARN: OpenClaw failed to start"
}
prepare_homeassistant() {
if [ "${ENABLE_HOMEASSISTANT:-1}" != "1" ] || ! need_docker; then
return 0
fi
log "Preparing Home Assistant"
mkdir -p "$HOMEASSISTANT_CONFIG_DIR"
chmod -R a+rwX "$HOMEASSISTANT_CONFIG_DIR" 2>/dev/null || true
allow_tcp_port_if_firewall_active "$HOMEASSISTANT_PORT"
if [ "${HOMEASSISTANT_AUTOSTART:-1}" != "1" ]; then
log "Home Assistant prepared; autostart disabled"
return 0
fi
compose_in_service_dir_timed "${HOMEASSISTANT_INSTALL_TIMEOUT:-${DOCKER_OPTIONAL_INSTALL_TIMEOUT:-900}}" "$ROOT_DIR/services/homeassistant/docker-compose.yml" up -d || \
log "WARN: Home Assistant failed to start"
}
prepare_frigate() {
if [ "${ENABLE_FRIGATE:-1}" != "1" ] || ! need_docker; then
return 0
fi
log "Preparing Frigate"
mkdir -p "$FRIGATE_CONFIG_DIR" "$FRIGATE_MEDIA_DIR"
if [ ! -s "$FRIGATE_CONFIG_DIR/config.yml" ] && [ -s "$ROOT_DIR/services/frigate/config/config.yml" ]; then
install -m 0666 "$ROOT_DIR/services/frigate/config/config.yml" "$FRIGATE_CONFIG_DIR/config.yml"
fi
chmod -R a+rwX "$FRIGATE_CONFIG_DIR" "$FRIGATE_MEDIA_DIR" 2>/dev/null || true
allow_tcp_port_if_firewall_active "$FRIGATE_WEB_PORT"
allow_tcp_port_if_firewall_active "$FRIGATE_RTSP_PORT"
allow_tcp_port_if_firewall_active "$FRIGATE_WEBRTC_PORT"
allow_udp_port_if_firewall_active "$FRIGATE_WEBRTC_PORT"
if [ "${FRIGATE_USB_AUTOSTART:-1}" = "1" ]; then
bash "$SERVICE_CTL" frigate auto || log "WARN: Frigate USB auto-start check failed"
install_frigate_usb_watch_service
else
compose_in_service_dir_timed "${FRIGATE_INSTALL_TIMEOUT:-${DOCKER_OPTIONAL_INSTALL_TIMEOUT:-900}}" "$ROOT_DIR/services/frigate/docker-compose.yml" up -d || \
log "WARN: Frigate failed to start"
fi
}
prepare_ntfy() {
if [ "${ENABLE_NTFY:-1}" != "1" ] || ! need_docker; then
return 0
fi
log "Preparing ntfy"
mkdir -p "$NTFY_CONFIG_DIR" "$NTFY_CACHE_DIR"
if [ ! -s "$NTFY_CONFIG_DIR/server.yml" ] && [ -s "$ROOT_DIR/services/ntfy/config/server.yml" ]; then
install -m 0666 "$ROOT_DIR/services/ntfy/config/server.yml" "$NTFY_CONFIG_DIR/server.yml"
sed -i "s#http://live.local:8089#http://${HOSTNAME_ALIAS}.local:${NTFY_PORT}#g" "$NTFY_CONFIG_DIR/server.yml" 2>/dev/null || true
fi
chmod -R a+rwX "$NTFY_CONFIG_DIR" "$NTFY_CACHE_DIR" 2>/dev/null || true
allow_tcp_port_if_firewall_active "$NTFY_PORT"
compose_in_service_dir_timed "${NTFY_INSTALL_TIMEOUT:-${DOCKER_OPTIONAL_INSTALL_TIMEOUT:-900}}" "$ROOT_DIR/services/ntfy/docker-compose.yml" up -d || \
log "WARN: ntfy failed to start"
}
prepare_coturn() {
if [ "${ENABLE_COTURN:-0}" != "1" ] || ! need_docker; then
return 0
fi
if [ -z "${COTURN_STATIC_AUTH_SECRET:-}" ] || [ "${COTURN_STATIC_AUTH_SECRET:-}" = "change-me" ]; then
log "WARN: coturn enabled but COTURN_STATIC_AUTH_SECRET is empty/unsafe; skipping TURN startup"
return 0
fi
log "Preparing coturn"
allow_udp_port_if_firewall_active "$COTURN_PORT"
allow_tcp_port_if_firewall_active "$COTURN_PORT"
allow_tcp_port_if_firewall_active "$COTURN_TLS_PORT"
allow_udp_range_if_firewall_active "${COTURN_MIN_PORT}-${COTURN_MAX_PORT}"
compose_in_service_dir_timed "${COTURN_INSTALL_TIMEOUT:-${DOCKER_OPTIONAL_INSTALL_TIMEOUT:-900}}" "$ROOT_DIR/services/coturn/docker-compose.yml" up -d || \
log "WARN: coturn failed to start"
}
install_frigate_usb_watch_service() {
if [ "${ENABLE_FRIGATE:-1}" != "1" ] || [ "${FRIGATE_USB_AUTOSTART:-1}" != "1" ]; then
systemctl disable --now live-frigate-usb-watch.service >/dev/null 2>&1 || true
rm -f /etc/systemd/system/live-frigate-usb-watch.service
return 0
fi
[ -f "$ROOT_DIR/scripts/linux/frigate_usb_watch.sh" ] || return 0
chmod +x "$ROOT_DIR/scripts/linux/frigate_usb_watch.sh"
cat >/etc/systemd/system/live-frigate-usb-watch.service <<UNIT
[Unit]
Description=Live Frigate USB/UVC camera watcher
After=docker.service network-online.target
Wants=docker.service network-online.target
[Service]
Type=simple
Environment=ROOT_DIR=$ROOT_DIR
Environment=FRIGATE_USB_SCAN_INTERVAL=$FRIGATE_USB_SCAN_INTERVAL
ExecStart=/bin/bash $ROOT_DIR/scripts/linux/frigate_usb_watch.sh
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now live-frigate-usb-watch.service >/dev/null 2>&1 || true
}
install_pulseaudio_service() {
if [ "${ENABLE_PULSEAUDIO:-1}" != "1" ]; then
return 0

View File

@ -6,7 +6,7 @@ INSTALL_TAG="${INSTALL_TAG:-neko-ip-watch}"
. "$SELF_DIR/lib/common.sh"
reload_watch_env() {
unset ENABLE_NEKO NEKO_IP_WATCH_INTERVAL
unset ENABLE_NEKO NEKO_ACCESS_MODE NEKO_WEBRTC_NAT1TO1 NEKO_IP_WATCH_INTERVAL
if [ -f "$STACK_ENV" ]; then
set -a
. "$STACK_ENV"
@ -54,14 +54,14 @@ maybe_refresh_neko_for_ip_change() {
fi
preferred="$(detect_preferred_lan_ip || true)"
if [ -z "$preferred" ]; then
return 0
fi
target="$preferred"
if neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then
target="$NEKO_WEBRTC_NAT1TO1"
elif neko_nat1to1_is_usable "${NEKO_WIREGUARD_HOST:-}"; then
target="$NEKO_WIREGUARD_HOST"
case "${NEKO_ACCESS_MODE:-lan}" in
remote)
target="${NEKO_WEBRTC_NAT1TO1:-}"
;;
esac
if [ -z "$target" ]; then
return 0
fi
active=""
@ -82,11 +82,11 @@ maybe_refresh_neko_for_ip_change() {
cooldown=15
fi
log "Detected Neko NAT1TO1 drift: container=${active} target=${target}; restarting Neko"
if bash "$SERVICE_CTL" neko restart; then
log "Neko restart finished; refreshed NAT1TO1=${target}"
log "Detected Neko NAT1TO1 drift: container=${active} target=${target}; reconfiguring Neko"
if bash "$SERVICE_CTL" neko reconfigure; then
log "Neko reconfigure finished; refreshed NAT1TO1=${target}"
else
log "WARN: Neko restart failed after LAN IP drift"
log "WARN: Neko reconfigure failed after NAT1TO1 drift"
fi
sleep "$cooldown"
}
@ -94,7 +94,7 @@ maybe_refresh_neko_for_ip_change() {
main() {
load_env
reload_watch_env
log "Watching Neko LAN IP changes"
log "Watching Neko access IP changes"
while true; do
reload_watch_env
maybe_refresh_neko_for_ip_change

View File

@ -8,6 +8,8 @@ INSTALL_TAG="refresh-unit"
ensure_root "$@"
load_env
ensure_live_user
ensure_live_can_traverse_repo_root
configure_host_dns
ensure_runtime_dirs_owned_by_live
log "Rewriting /etc/systemd/system/live-console.service from repo"
@ -15,4 +17,6 @@ install_live_console_service
ensure_runtime_dirs_owned_by_live
log "Rewriting /etc/systemd/system/live-neko-ip-watch.service from repo"
install_neko_ip_watch_service
log "Rewriting /etc/systemd/system/live-frigate-usb-watch.service from repo"
install_frigate_usb_watch_service
log "Done. Check: systemctl status live-console.service --no-pager"

View File

@ -18,6 +18,10 @@ MITMPROXY_COMPOSE="$ROOT_DIR/services/mitmproxy/docker-compose.yml"
VSCODE_SERVER_COMPOSE="$ROOT_DIR/services/vscode-server/docker-compose.yml"
UPTIME_KUMA_COMPOSE="$ROOT_DIR/services/uptime-kuma/docker-compose.yml"
OPENCLAW_COMPOSE="$ROOT_DIR/services/openclaw/docker-compose.yml"
HOMEASSISTANT_COMPOSE="$ROOT_DIR/services/homeassistant/docker-compose.yml"
FRIGATE_COMPOSE="$ROOT_DIR/services/frigate/docker-compose.yml"
NTFY_COMPOSE="$ROOT_DIR/services/ntfy/docker-compose.yml"
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"
@ -36,6 +40,16 @@ SRS_API_PORT="${SRS_API_PORT:-1985}"
SRS_SRT_PORT="${SRS_SRT_PORT:-10080}"
SRS_WEBRTC_PORT="${SRS_WEBRTC_PORT:-8088}"
SHELLCRASH_DIR="${SHELLCRASH_DIR:-/etc/ShellCrash}"
SHELLCRASH_AUTOSTART="${SHELLCRASH_AUTOSTART:-0}"
SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL="${SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL:-1}"
SHELLCRASH_MANUAL_ONLY="${SHELLCRASH_MANUAL_ONLY:-1}"
SHELLCRASH_AUTO_START_ON_WEB_PANEL="${SHELLCRASH_AUTO_START_ON_WEB_PANEL:-0}"
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}"
NETWORK_PROBE_GOOGLE_URL="${NETWORK_PROBE_GOOGLE_URL:-https://www.google.com/generate_204}"
NETWORK_PROBE_YOUTUBE_URL="${NETWORK_PROBE_YOUTUBE_URL:-https://www.youtube.com/generate_204}"
NETWORK_PROBE_DOUYIN_URL="${NETWORK_PROBE_DOUYIN_URL:-https://live.douyin.com/}"
WEBTTY_USER="${WEBTTY_USER:-live}"
WEBTTY_PASS="${WEBTTY_PASS:-12345678}"
FILEBROWSER_USER="${FILEBROWSER_USER:-live}"
@ -73,6 +87,7 @@ NEKO_WEBRTC_EPR="${NEKO_WEBRTC_EPR:-$NEKO_WEBRTC_UDP_RANGE_1}"
NEKO_WEBRTC_EPR_1="${NEKO_WEBRTC_EPR_1:-$NEKO_WEBRTC_EPR}"
NEKO_WEBRTC_EPR_2="${NEKO_WEBRTC_EPR_2:-$NEKO_WEBRTC_UDP_RANGE_2}"
NEKO_WEBRTC_EPR_3="${NEKO_WEBRTC_EPR_3:-$NEKO_WEBRTC_UDP_RANGE_3}"
NEKO_ACCESS_MODE="${NEKO_ACCESS_MODE:-lan}"
NEKO_START_URL="${NEKO_START_URL:-https://accounts.google.com/ServiceLogin?continue=https://www.youtube.com/}"
NEKO_IMAGE_X86="${NEKO_IMAGE_X86:-ghcr.io/m1k1o/neko/google-chrome:3.0.0}"
NEKO_IMAGE_ARM64="${NEKO_IMAGE_ARM64:-ghcr.io/m1k1o/neko/chromium:3.0.0}"
@ -109,6 +124,40 @@ OPENCLAW_GATEWAY_TOKEN="${OPENCLAW_GATEWAY_TOKEN:-12345678}"
OPENCLAW_ALLOW_INSECURE_PRIVATE_WS="${OPENCLAW_ALLOW_INSECURE_PRIVATE_WS:-1}"
OPENCLAW_CONFIG_DIR="${OPENCLAW_CONFIG_DIR:-/var/lib/live-openclaw/config}"
OPENCLAW_WORKSPACE_DIR="${OPENCLAW_WORKSPACE_DIR:-/var/lib/live-openclaw/workspace}"
ENABLE_HOMEASSISTANT="${ENABLE_HOMEASSISTANT:-1}"
HOMEASSISTANT_AUTOSTART="${HOMEASSISTANT_AUTOSTART:-1}"
HOMEASSISTANT_IMAGE="${HOMEASSISTANT_IMAGE:-ghcr.io/home-assistant/home-assistant:stable}"
HOMEASSISTANT_PORT="${HOMEASSISTANT_PORT:-8123}"
HOMEASSISTANT_CONFIG_DIR="${HOMEASSISTANT_CONFIG_DIR:-/var/lib/live-homeassistant/config}"
ENABLE_FRIGATE="${ENABLE_FRIGATE:-1}"
FRIGATE_USB_AUTOSTART="${FRIGATE_USB_AUTOSTART:-1}"
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}"
FRIGATE_RTSP_PORT="${FRIGATE_RTSP_PORT:-8554}"
FRIGATE_WEBRTC_PORT="${FRIGATE_WEBRTC_PORT:-8555}"
FRIGATE_SHM_SIZE="${FRIGATE_SHM_SIZE:-256mb}"
FRIGATE_CONFIG_DIR="${FRIGATE_CONFIG_DIR:-/var/lib/live-frigate/config}"
FRIGATE_MEDIA_DIR="${FRIGATE_MEDIA_DIR:-/var/lib/live-frigate/media}"
FRIGATE_PRIVILEGED="${FRIGATE_PRIVILEGED:-true}"
ENABLE_WOL="${ENABLE_WOL:-1}"
WOL_BROADCAST="${WOL_BROADCAST:-255.255.255.255}"
WOL_PORT="${WOL_PORT:-9}"
WOL_PROBE_INTERVAL="${WOL_PROBE_INTERVAL:-30}"
WOL_PROBE_CIDR="${WOL_PROBE_CIDR:-}"
ENABLE_NTFY="${ENABLE_NTFY:-1}"
NTFY_IMAGE="${NTFY_IMAGE:-binwiederhier/ntfy:latest}"
NTFY_PORT="${NTFY_PORT:-8089}"
NTFY_CONFIG_DIR="${NTFY_CONFIG_DIR:-/var/lib/live-ntfy/config}"
NTFY_CACHE_DIR="${NTFY_CACHE_DIR:-/var/lib/live-ntfy/cache}"
ENABLE_COTURN="${ENABLE_COTURN:-0}"
COTURN_IMAGE="${COTURN_IMAGE:-coturn/coturn:latest}"
COTURN_PORT="${COTURN_PORT:-3478}"
COTURN_TLS_PORT="${COTURN_TLS_PORT:-5349}"
COTURN_MIN_PORT="${COTURN_MIN_PORT:-49160}"
COTURN_MAX_PORT="${COTURN_MAX_PORT:-49200}"
COTURN_REALM="${COTURN_REALM:-live.local}"
COTURN_STATIC_AUTH_SECRET="${COTURN_STATIC_AUTH_SECRET:-}"
ENABLE_REDROID="${ENABLE_REDROID:-1}"
REDROID_DEFAULT_PORT="${REDROID_DEFAULT_PORT:-5555}"
REDROID_INSTANCE_PREFIX="${REDROID_INSTANCE_PREFIX:-redroid13}"
@ -148,6 +197,13 @@ have() {
command -v "$1" >/dev/null 2>&1
}
flag_enabled() {
case "${1:-}" in
1|true|TRUE|yes|YES|on|ON|enable|enabled) return 0 ;;
*) return 1 ;;
esac
}
allow_tcp_port_if_firewall_active() {
local port="$1"
if have ufw && ufw status 2>/dev/null | grep -q '^Status: active'; then
@ -611,17 +667,29 @@ remove_legacy_neko_container() {
fi
}
detect_preferred_lan_ip() {
local src iface candidate path name
is_physical_lan_iface_name() {
local name="${1:-}"
case "$name" in
""|lo|docker*|br-*|veth*|virbr*|tun*|tap*|zt*|tailscale*|wg*|wireguard*|sit*|dummy*|p2p-dev-*|mon.*)
return 1
;;
esac
return 0
}
src="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for (i=1; i<=NF; i++) if ($i=="src") {print $(i+1); exit}}')"
if [ -n "$src" ]; then
detect_preferred_lan_ip() {
local route src iface candidate path name
route="$(ip -4 route get 1.1.1.1 2>/dev/null || true)"
src="$(printf '%s\n' "$route" | awk '{for (i=1; i<=NF; i++) if ($i=="src") {print $(i+1); exit}}')"
iface="$(printf '%s\n' "$route" | awk '{for (i=1; i<=NF; i++) if ($i=="dev") {print $(i+1); exit}}')"
if [ -n "$src" ] && is_physical_lan_iface_name "$iface"; then
printf '%s\n' "$src"
return 0
fi
iface="$(ip route show default 2>/dev/null | awk 'NR==1 {print $5}')"
if [ -n "$iface" ]; then
if is_physical_lan_iface_name "$iface"; then
src="$(ip -4 addr show dev "$iface" 2>/dev/null | awk '$1=="inet" {sub(/\/.*/, "", $2); print $2; exit}')"
if [ -n "$src" ]; then
printf '%s\n' "$src"
@ -632,11 +700,7 @@ detect_preferred_lan_ip() {
for path in /sys/class/net/*; do
[ -e "$path" ] || continue
name="${path##*/}"
case "$name" in
lo|docker*|br-*|veth*|virbr*|tun*|tap*|zt*|tailscale*|wg*|sit*|dummy*|p2p-dev-*|mon.*)
continue
;;
esac
is_physical_lan_iface_name "$name" || continue
candidate="$(ip -4 addr show dev "$name" 2>/dev/null | awk '$1=="inet" {sub(/\/.*/, "", $2); print $2; exit}')"
if [ -n "$candidate" ]; then
printf '%s\n' "$candidate"
@ -711,8 +775,8 @@ neko_nat1to1_is_usable() {
return 1
;;
*)
# Explicit NAT1TO1 may intentionally be a WireGuard/Tailscale/EasyTier address.
# Auto-detection still prefers physical LAN via detect_preferred_lan_ip().
# Explicit NAT1TO1 may be a physical LAN or WireGuard address, but auto-detection
# stays on the physical LAN path via detect_preferred_lan_ip().
return 0
;;
esac
@ -858,10 +922,77 @@ shellcrash_mix_port() {
printf '%s' "$port"
}
shellcrash_config_available() {
[ -s "$SHELLCRASH_DIR/yamls/config.yaml" ] || [ -s "/tmp/ShellCrash/config.yaml" ]
}
system_probe_url() {
local url="$1"
[ -n "$url" ] || return 1
if have curl; then
curl -kfsSL --connect-timeout 3 --max-time 5 --noproxy '*' -o /dev/null "$url" 2>/dev/null && return 0
elif have wget; then
env -u http_proxy -u https_proxy -u HTTP_PROXY -u HTTPS_PROXY -u all_proxy -u ALL_PROXY \
wget -q --no-check-certificate --timeout=5 -O /dev/null "$url" 2>/dev/null && return 0
fi
return 1
}
system_direct_global_ready() {
flag_enabled "${SHELLCRASH_FORCE_PROXY:-0}" && return 1
system_probe_url "$NETWORK_PROBE_GOOGLE_URL" && return 0
system_probe_url "$NETWORK_PROBE_YOUTUBE_URL" && return 0
return 1
}
shellcrash_should_autostart_on_direct_fail() {
flag_enabled "$SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL" || return 1
system_direct_global_ready && return 1
shellcrash_config_available
}
shellcrash_set_systemd_autostart_for_policy() {
if shellcrash_should_autostart_on_direct_fail; then
systemctl enable shellcrash.service >/dev/null 2>&1 || true
else
systemctl disable shellcrash.service >/dev/null 2>&1 || true
fi
}
shellcrash_autostart_if_needed() {
shellcrash_should_autostart_on_direct_fail || return 1
shellcrash_sync_runtime_config >/dev/null 2>&1 || return 1
shellcrash_prepare_runtime >/dev/null 2>&1 || return 1
if unit_exists shellcrash.service; then
systemctl reset-failed shellcrash.service >/dev/null 2>&1 || true
systemctl enable --now shellcrash.service >/dev/null 2>&1 || return 1
elif [ -x "$SHELLCRASH_DIR/start.sh" ]; then
"$SHELLCRASH_DIR/start.sh" start >/dev/null 2>&1 || return 1
else
return 1
fi
return 0
}
neko_default_proxy_bypass() {
printf '%s' '<-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'
}
shellcrash_proxy_available() {
local port="$1"
[ "${ENABLE_SHELLCRASH:-1}" = "1" ] || return 1
if unit_exists shellcrash.service && ! unit_active shellcrash.service; then
return 1
fi
if have ss; then
ss -ltn 2>/dev/null | awk -v p=":$port" '
$4 ~ p"$" && $4 !~ /(^|:)127\.0\.0\.1:/ && $4 !~ /\[::1\]:/ { found=1 }
END { exit(found ? 0 : 1) }
' && return 0
fi
return 1
}
resolve_neko_browser_proxy() {
case "${NEKO_BROWSER_PROXY:-}" in
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
@ -873,8 +1004,20 @@ resolve_neko_browser_proxy() {
return 0
;;
esac
[ "${ENABLE_SHELLCRASH:-1}" = "1" ] || return 0
printf 'http://host.docker.internal:%s' "$(shellcrash_mix_port)"
case "$SHELLCRASH_ATTACH_NEKO" in
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
return 0
;;
esac
if ! flag_enabled "$SHELLCRASH_ATTACH_WHEN_DIRECT_OK" && system_direct_global_ready; then
return 0
fi
shellcrash_autostart_if_needed >/dev/null 2>&1 || true
local port
port="$(shellcrash_mix_port)"
if shellcrash_proxy_available "$port"; then
printf 'http://host.docker.internal:%s' "$port"
fi
}
ensure_neko_browser_launcher_executable() {
@ -958,6 +1101,28 @@ shellcrash_prepare_runtime() {
[ -x /tmp/ShellCrash/CrashCore ]
}
shellcrash_systemd_start() {
systemctl reset-failed shellcrash.service >/dev/null 2>&1 || true
if shellcrash_should_autostart_on_direct_fail; then
systemctl enable --now shellcrash.service
else
systemctl disable shellcrash.service >/dev/null 2>&1 || true
systemctl start shellcrash.service
systemctl disable shellcrash.service >/dev/null 2>&1 || true
fi
}
shellcrash_systemd_restart() {
systemctl reset-failed shellcrash.service >/dev/null 2>&1 || true
if shellcrash_should_autostart_on_direct_fail; then
systemctl enable shellcrash.service >/dev/null 2>&1 || true
else
systemctl disable shellcrash.service >/dev/null 2>&1 || true
fi
systemctl restart shellcrash.service
shellcrash_set_systemd_autostart_for_policy
}
shellcrash_web_panel_installed() {
local index="$SHELLCRASH_DIR/ui/index.html"
[ -s "$index" ] || return 1
@ -1053,7 +1218,7 @@ ensure_shellcrash_web_panel() {
}
service_shellcrash_status() {
local running detail
local running detail enabled
if [ ! -x "$SHELLCRASH_DIR/start.sh" ] && ! unit_exists shellcrash.service; then
kv available 0
kv running 0
@ -1066,6 +1231,15 @@ service_shellcrash_status() {
if unit_active shellcrash.service || [ -n "$detail" ]; then
running=1
fi
if [ "$running" != 1 ] && shellcrash_should_autostart_on_direct_fail; then
shellcrash_autostart_if_needed >/dev/null 2>&1 || true
detail="$(filtered_pgrep '(^|[ /])CrashCore([ ]|$)' | tr '\n' ';' || true)"
if unit_active shellcrash.service || [ -n "$detail" ]; then
running=1
fi
fi
shellcrash_set_systemd_autostart_for_policy
enabled="$(systemctl is-enabled shellcrash.service 2>/dev/null || true)"
[ -z "$detail" ] && detail="dir=$SHELLCRASH_DIR"
kv available 1
kv running "$running"
@ -1073,7 +1247,8 @@ service_shellcrash_status() {
kv url "$(shellcrash_web_url)"
kv host "${HOSTNAME_ALIAS}.local"
kv port "$(shellcrash_web_port)"
kv detail "$detail"
kv autostart "$([ "$enabled" = enabled ] && echo 1 || echo 0)"
kv detail "$detail; direct_google=$(system_direct_global_ready && echo ok || echo fail); config=$(shellcrash_config_available && echo 1 || echo 0); autostart=${enabled:-disabled}"
}
service_shellcrash_start() {
@ -1089,10 +1264,13 @@ service_shellcrash_start() {
kv message "ShellCrash CrashCore is missing; check DNS/network and rerun apply"
exit 1
fi
if [ -x "$SHELLCRASH_DIR/start.sh" ]; then
if unit_exists shellcrash.service; then
shellcrash_systemd_start
elif [ -x "$SHELLCRASH_DIR/start.sh" ]; then
"$SHELLCRASH_DIR/start.sh" start
else
systemctl enable --now shellcrash.service
kv message "ShellCrash is not installed"
exit 1
fi
kv message "ShellCrash started"
}
@ -1110,17 +1288,20 @@ service_shellcrash_restart() {
kv message "ShellCrash CrashCore is missing; check DNS/network and rerun apply"
exit 1
fi
if [ -x "$SHELLCRASH_DIR/start.sh" ]; then
if unit_exists shellcrash.service; then
shellcrash_systemd_restart
elif [ -x "$SHELLCRASH_DIR/start.sh" ]; then
"$SHELLCRASH_DIR/start.sh" restart
else
systemctl restart shellcrash.service
kv message "ShellCrash is not installed"
exit 1
fi
kv message "ShellCrash restarted"
}
service_shellcrash_stop() {
if unit_exists shellcrash.service; then
systemctl stop shellcrash.service
systemctl disable --now shellcrash.service >/dev/null 2>&1 || systemctl stop shellcrash.service
elif [ -x "$SHELLCRASH_DIR/start.sh" ]; then
"$SHELLCRASH_DIR/start.sh" stop
fi
@ -1132,12 +1313,13 @@ service_shellcrash_web_panel() {
exit 1
fi
shellcrash_sync_runtime_config >/dev/null 2>&1 || true
if ! unit_active shellcrash.service && [ -z "$(filtered_pgrep '(^|[ /])CrashCore([ ]|$)' || true)" ]; then
if { flag_enabled "$SHELLCRASH_AUTO_START_ON_WEB_PANEL" || shellcrash_should_autostart_on_direct_fail; } && ! unit_active shellcrash.service && [ -z "$(filtered_pgrep '(^|[ /])CrashCore([ ]|$)' || true)" ]; then
service_shellcrash_start >/dev/null
fi
kv message "ShellCrash web panel ready"
kv url "$(shellcrash_web_url)"
kv port "$(shellcrash_web_port)"
kv manual_only "$SHELLCRASH_MANUAL_ONLY"
}
grant_shellcrash_web_write_access() {
@ -1234,8 +1416,7 @@ EOF
sed -i "s#^ExecStart=.*#ExecStart=/tmp/ShellCrash/CrashCore -d $SHELLCRASH_DIR -f /tmp/ShellCrash/config.yaml#" "$unit_path"
systemctl daemon-reload
fi
systemctl reset-failed shellcrash.service >/dev/null 2>&1 || true
systemctl restart shellcrash.service
shellcrash_systemd_restart
elif [ -x "$SHELLCRASH_DIR/start.sh" ]; then
"$SHELLCRASH_DIR/start.sh" restart
else
@ -1618,11 +1799,7 @@ service_neko_status() {
kv host "${HOSTNAME_ALIAS}.local"
kv port "$NEKO_HTTP_PORT_1"
kv url "http://${HOSTNAME_ALIAS}.local:${NEKO_HTTP_PORT_1}"
if neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then
:
elif neko_nat1to1_is_usable "${NEKO_WIREGUARD_HOST:-}"; then
NEKO_WEBRTC_NAT1TO1="$NEKO_WIREGUARD_HOST"
else
if ! neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then
NEKO_WEBRTC_NAT1TO1="$(detect_preferred_lan_ip || true)"
fi
browser_proxy="${NEKO_BROWSER_PROXY:-$(resolve_neko_browser_proxy)}"
@ -1665,6 +1842,28 @@ service_neko_start() {
kv message "Neko stack started (${instance_count} browser instances)"
}
service_neko_reconfigure() {
if [ "${ENABLE_NEKO:-1}" != "1" ]; then
kv message "Neko disabled"
exit 1
fi
if [ ! -f "$ROOT_DIR/tools/render_neko_compose.py" ]; then
kv message "Neko compose renderer missing"
return 0
fi
local idx instance_count compose_file service_names=""
instance_count="$(resolve_neko_instance_count)"
export_neko_env
for idx in $(seq 1 "$instance_count"); do
service_names="${service_names} neko${idx}"
done
compose_file="$(render_neko_compose_file)"
# 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
kv message "Neko WebRTC config reapplied (${instance_count} browser instances)"
}
export_neko_env() {
export NEKO_HTTP_PORT="${NEKO_HTTP_PORT:-9200}"
export NEKO_HTTP_PORT_1="${NEKO_HTTP_PORT_1:-$NEKO_HTTP_PORT}"
@ -1704,6 +1903,7 @@ export_neko_env() {
export NEKO_WEBRTC_EPR_1="${NEKO_WEBRTC_EPR_1:-$NEKO_WEBRTC_EPR}"
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}"
# 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
@ -1719,11 +1919,7 @@ export_neko_env() {
export NEKO_WEBRTC_UDPMUX_1="${NEKO_WEBRTC_UDPMUX_1:-$NEKO_WEBRTC_UDPMUX}"
export NEKO_WEBRTC_UDPMUX_2="${NEKO_WEBRTC_UDPMUX_2:-52301}"
export NEKO_WEBRTC_UDPMUX_3="${NEKO_WEBRTC_UDPMUX_3:-52302}"
if neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then
export NEKO_WEBRTC_NAT1TO1
elif neko_nat1to1_is_usable "${NEKO_WIREGUARD_HOST:-}"; then
export NEKO_WEBRTC_NAT1TO1="$NEKO_WIREGUARD_HOST"
else
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}"
@ -1954,6 +2150,334 @@ service_openclaw_stop() {
kv message "OpenClaw stopped"
}
service_homeassistant_status() {
if [ "${ENABLE_HOMEASSISTANT:-1}" != "1" ]; then
kv available 0
kv running 0
kv status unavailable
kv detail "Set ENABLE_HOMEASSISTANT=1 in config/system-stack.env to enable Home Assistant"
return 0
fi
if ! have docker || [ ! -f "$HOMEASSISTANT_COMPOSE" ]; then
kv available 0
kv running 0
kv status unavailable
kv detail "Docker or Home Assistant compose file is missing"
return 0
fi
local state
state="$(docker_container_status live-homeassistant || true)"
kv available 1
kv running "$([[ "$state" == running* ]] && echo 1 || echo 0)"
kv status "$([[ "$state" == running* ]] && echo online || echo stopped)"
kv host "${HOSTNAME_ALIAS}.local"
kv port "$HOMEASSISTANT_PORT"
kv url "http://${HOSTNAME_ALIAS}.local:${HOMEASSISTANT_PORT}"
kv detail "${state:-container=missing};config=${HOMEASSISTANT_CONFIG_DIR};network=host"
}
service_homeassistant_start() {
mkdir -p "$HOMEASSISTANT_CONFIG_DIR"
chmod -R a+rwX "$HOMEASSISTANT_CONFIG_DIR" 2>/dev/null || true
compose_in_service_dir "$HOMEASSISTANT_COMPOSE" up -d
kv message "Home Assistant started"
}
service_homeassistant_stop() {
compose_in_service_dir "$HOMEASSISTANT_COMPOSE" down
kv message "Home Assistant stopped"
}
frigate_detect_usb_cameras() {
local dev base props name bus
for dev in /dev/video*; do
[ -e "$dev" ] || continue
base="$(basename "$dev")"
props="$(udevadm info -q property -n "$dev" 2>/dev/null || true)"
name="$(cat "/sys/class/video4linux/${base}/name" 2>/dev/null || true)"
bus="$(printf '%s\n' "$props" | awk -F= '$1=="ID_BUS"{print $2; exit}')"
if [ "$bus" = "usb" ] || printf '%s\n%s\n' "$props" "$name" | grep -Eiq 'uvc|usb|webcam|camera'; then
printf '%s|%s\n' "$dev" "${name:-USB camera}"
fi
done
}
render_frigate_usb_config() {
local devices="$1" cfg="$FRIGATE_CONFIG_DIR/config.yml" dev name cam
mkdir -p "$FRIGATE_CONFIG_DIR"
if [ -s "$cfg" ] && ! grep -q 'Managed by live stack USB camera autodetect' "$cfg" 2>/dev/null; then
return 0
fi
{
printf '%s\n' '# Managed by live stack USB camera autodetect'
printf '%s\n' 'mqtt:'
printf '%s\n' ' enabled: false'
printf '%s\n' ''
printf '%s\n' 'detectors:'
printf '%s\n' ' cpu1:'
printf '%s\n' ' type: cpu'
printf '%s\n' ''
if [ -z "$devices" ]; then
printf '%s\n' 'cameras: {}'
else
printf '%s\n' 'cameras:'
printf '%s\n' "$devices" | while IFS='|' read -r dev name; do
[ -n "$dev" ] || continue
cam="$(basename "$dev" | tr -c 'A-Za-z0-9_' '_')"
printf ' usb_%s:\n' "$cam"
printf ' enabled: true\n'
printf ' ffmpeg:\n'
printf ' inputs:\n'
printf ' - path: %s\n' "$dev"
printf ' input_args:\n'
printf ' - -f\n'
printf ' - v4l2\n'
printf ' - -input_format\n'
printf ' - mjpeg\n'
printf ' - -video_size\n'
printf ' - 640x480\n'
printf ' - -framerate\n'
printf ' - "5"\n'
printf ' roles:\n'
printf ' - detect\n'
printf ' detect:\n'
printf ' enabled: true\n'
printf ' width: 640\n'
printf ' height: 480\n'
printf ' fps: 5\n'
done
fi
} >"$cfg"
chmod a+rw "$cfg" 2>/dev/null || true
}
ensure_frigate_default_config() {
mkdir -p "$FRIGATE_CONFIG_DIR" "$FRIGATE_MEDIA_DIR"
if [ ! -s "$FRIGATE_CONFIG_DIR/config.yml" ] && [ -s "$ROOT_DIR/services/frigate/config/config.yml" ]; then
install -m 0666 "$ROOT_DIR/services/frigate/config/config.yml" "$FRIGATE_CONFIG_DIR/config.yml"
fi
chmod -R a+rwX "$FRIGATE_CONFIG_DIR" "$FRIGATE_MEDIA_DIR" 2>/dev/null || true
}
service_frigate_status() {
if [ "${ENABLE_FRIGATE:-1}" != "1" ]; then
kv available 0
kv running 0
kv status unavailable
kv detail "Set ENABLE_FRIGATE=1 in config/system-stack.env to enable Frigate"
return 0
fi
if ! have docker || [ ! -f "$FRIGATE_COMPOSE" ]; then
kv available 0
kv running 0
kv status unavailable
kv detail "Docker or Frigate compose file is missing"
return 0
fi
local state
state="$(docker_container_status live-frigate || true)"
local usb_count
usb_count="$(frigate_detect_usb_cameras | awk 'NF{n++} END{print n+0}')"
kv available 1
kv running "$([[ "$state" == running* ]] && echo 1 || echo 0)"
kv status "$([[ "$state" == running* ]] && echo online || echo stopped)"
kv host "${HOSTNAME_ALIAS}.local"
kv port "$FRIGATE_WEB_PORT"
kv url "http://${HOSTNAME_ALIAS}.local:${FRIGATE_WEB_PORT}"
kv detail "${state:-container=missing};usb_cameras=${usb_count};rtsp=${FRIGATE_RTSP_PORT};webrtc=${FRIGATE_WEBRTC_PORT};config=${FRIGATE_CONFIG_DIR};media=${FRIGATE_MEDIA_DIR}"
}
service_frigate_start() {
ensure_frigate_default_config
render_frigate_usb_config "$(frigate_detect_usb_cameras || true)"
compose_in_service_dir "$FRIGATE_COMPOSE" up -d
kv message "Frigate started"
}
service_frigate_stop() {
compose_in_service_dir "$FRIGATE_COMPOSE" down
kv message "Frigate stopped"
}
service_frigate_auto() {
if [ "${ENABLE_FRIGATE:-1}" != "1" ] || [ "${FRIGATE_USB_AUTOSTART:-1}" != "1" ]; then
kv message "Frigate USB autostart disabled"
return 0
fi
local devices count state
devices="$(frigate_detect_usb_cameras || true)"
count="$(printf '%s\n' "$devices" | awk 'NF{n++} END{print n+0}')"
if [ "$count" -le 0 ]; then
kv message "No USB/UVC camera detected"
return 0
fi
render_frigate_usb_config "$devices"
state="$(docker_container_status live-frigate || true)"
if [[ "$state" == running* ]]; then
kv message "Frigate already running; usb_cameras=${count}"
return 0
fi
compose_in_service_dir "$FRIGATE_COMPOSE" up -d
kv message "Frigate auto-started; usb_cameras=${count}"
}
normalize_wol_mac() {
printf '%s' "$1" | tr '[:lower:]' '[:upper:]' | sed 's/[^0-9A-F]//g'
}
service_wol_status() {
if [ "${ENABLE_WOL:-1}" != "1" ]; then
kv available 0
kv running 0
kv status unavailable
kv detail "Set ENABLE_WOL=1 in config/system-stack.env to enable Wake-on-LAN"
return 0
fi
kv available 1
kv running 0
kv status ready
kv host "${HOSTNAME_ALIAS}.local"
kv port "$WOL_PORT"
kv url "${CONSOLE_BASE_URL}/?view=studio"
kv detail "broadcast=${WOL_BROADCAST};port=${WOL_PORT};send_magic_packet"
}
service_wol_start() {
kv message "Wake-on-LAN is ready; use the Studio WOL form or service_ctl wol wake <mac>"
}
service_wol_stop() {
kv message "Wake-on-LAN has no background daemon to stop"
}
service_wol_wake() {
local mac="${ACTION_ARG1:-}" broadcast="${ACTION_ARG2:-$WOL_BROADCAST}" port="${WOL_PORT:-9}" clean
clean="$(normalize_wol_mac "$mac")"
if [ "${#clean}" -ne 12 ]; then
kv message "Invalid MAC address"
exit 1
fi
python3 - "$clean" "$broadcast" "$port" <<'PY'
import socket
import sys
mac, broadcast, port = sys.argv[1], sys.argv[2], int(sys.argv[3])
payload = bytes.fromhex("FF" * 6 + mac * 16)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(payload, (broadcast, port))
finally:
sock.close()
PY
kv message "Wake-on-LAN packet sent to $mac via $broadcast:$port"
}
ensure_ntfy_default_config() {
mkdir -p "$NTFY_CONFIG_DIR" "$NTFY_CACHE_DIR"
if [ ! -s "$NTFY_CONFIG_DIR/server.yml" ] && [ -s "$ROOT_DIR/services/ntfy/config/server.yml" ]; then
install -m 0666 "$ROOT_DIR/services/ntfy/config/server.yml" "$NTFY_CONFIG_DIR/server.yml"
sed -i "s#http://live.local:8089#http://${HOSTNAME_ALIAS}.local:${NTFY_PORT}#g" "$NTFY_CONFIG_DIR/server.yml" 2>/dev/null || true
fi
chmod -R a+rwX "$NTFY_CONFIG_DIR" "$NTFY_CACHE_DIR" 2>/dev/null || true
}
service_ntfy_status() {
if [ "${ENABLE_NTFY:-1}" != "1" ]; then
kv available 0
kv running 0
kv status unavailable
kv detail "Set ENABLE_NTFY=1 in config/system-stack.env to enable ntfy"
return 0
fi
if ! have docker || [ ! -f "$NTFY_COMPOSE" ]; then
kv available 0
kv running 0
kv status unavailable
kv detail "Docker or ntfy compose file is missing"
return 0
fi
local state
state="$(docker_container_status live-ntfy || true)"
kv available 1
kv running "$([[ "$state" == running* ]] && echo 1 || echo 0)"
kv status "$([[ "$state" == running* ]] && echo online || echo stopped)"
kv host "${HOSTNAME_ALIAS}.local"
kv port "$NTFY_PORT"
kv url "http://${HOSTNAME_ALIAS}.local:${NTFY_PORT}"
kv detail "${state:-container=missing};config=${NTFY_CONFIG_DIR};cache=${NTFY_CACHE_DIR}"
}
service_ntfy_start() {
ensure_ntfy_default_config
compose_in_service_dir "$NTFY_COMPOSE" up -d
kv message "ntfy started"
}
service_ntfy_stop() {
compose_in_service_dir "$NTFY_COMPOSE" down
kv message "ntfy stopped"
}
coturn_secret_ready() {
[ -n "${COTURN_STATIC_AUTH_SECRET:-}" ] && [ "${COTURN_STATIC_AUTH_SECRET:-}" != "change-me" ]
}
service_coturn_status() {
if [ "${ENABLE_COTURN:-0}" != "1" ]; then
kv available 0
kv running 0
kv status unavailable
kv detail "Set ENABLE_COTURN=1 and COTURN_STATIC_AUTH_SECRET in config/system-stack.env to enable TURN relay"
return 0
fi
if ! coturn_secret_ready; then
kv available 0
kv running 0
kv status unsafe
kv detail "COTURN_STATIC_AUTH_SECRET is empty or unsafe; refusing to run an open TURN relay"
return 0
fi
if ! have docker || [ ! -f "$COTURN_COMPOSE" ]; then
kv available 0
kv running 0
kv status unavailable
kv detail "Docker or coturn compose file is missing"
return 0
fi
local state
state="$(docker_container_status live-coturn || true)"
kv available 1
kv running "$([[ "$state" == running* ]] && echo 1 || echo 0)"
kv status "$([[ "$state" == running* ]] && echo online || echo stopped)"
kv host "${HOSTNAME_ALIAS}.local"
kv port "$COTURN_PORT"
kv url "turn:${HOSTNAME_ALIAS}.local:${COTURN_PORT}?transport=udp"
kv detail "${state:-container=missing};turn=${COTURN_PORT};turns=${COTURN_TLS_PORT};relay=${COTURN_MIN_PORT}-${COTURN_MAX_PORT};realm=${COTURN_REALM}"
}
service_coturn_start() {
if [ "${ENABLE_COTURN:-0}" != "1" ]; then
kv message "Set ENABLE_COTURN=1 first"
exit 1
fi
if ! coturn_secret_ready; then
kv message "Set a non-empty COTURN_STATIC_AUTH_SECRET before starting coturn"
exit 1
fi
allow_udp_port_if_firewall_active "$COTURN_PORT"
allow_tcp_port_if_firewall_active "$COTURN_PORT"
allow_tcp_port_if_firewall_active "$COTURN_TLS_PORT"
allow_udp_range_if_firewall_active "${COTURN_MIN_PORT}:${COTURN_MAX_PORT}"
compose_in_service_dir "$COTURN_COMPOSE" up -d
kv message "coturn started"
}
service_coturn_stop() {
compose_in_service_dir "$COTURN_COMPOSE" down
kv message "coturn stopped"
}
redroid_default_name() {
printf '%s' "${REDROID_INSTANCE_PREFIX}-1"
}

View File

@ -0,0 +1,19 @@
services:
coturn:
image: "${COTURN_IMAGE:-coturn/coturn:latest}"
container_name: live-coturn
restart: unless-stopped
network_mode: host
command:
- -n
- --fingerprint
- --lt-cred-mech
- --use-auth-secret
- "--static-auth-secret=${COTURN_STATIC_AUTH_SECRET:?set COTURN_STATIC_AUTH_SECRET}"
- "--realm=${COTURN_REALM:-live.local}"
- "--listening-port=${COTURN_PORT:-3478}"
- "--tls-listening-port=${COTURN_TLS_PORT:-5349}"
- "--min-port=${COTURN_MIN_PORT:-49160}"
- "--max-port=${COTURN_MAX_PORT:-49200}"
- "--log-file=stdout"
- --no-cli

View File

@ -0,0 +1,8 @@
mqtt:
enabled: false
detectors:
cpu1:
type: cpu
cameras: {}

View File

@ -0,0 +1,20 @@
services:
frigate:
image: "${FRIGATE_IMAGE:-ghcr.io/blakeblackshear/frigate:stable}"
container_name: live-frigate
restart: unless-stopped
privileged: "${FRIGATE_PRIVILEGED:-true}"
shm_size: "${FRIGATE_SHM_SIZE:-256mb}"
environment:
TZ: "${TZ:-UTC}"
FRIGATE_RTSP_PASSWORD: "${FRIGATE_RTSP_PASSWORD:-live12345678}"
ports:
- "${FRIGATE_WEB_PORT:-5001}:5000"
- "${FRIGATE_RTSP_PORT:-8554}:8554"
- "${FRIGATE_WEBRTC_PORT:-8555}:8555/tcp"
- "${FRIGATE_WEBRTC_PORT:-8555}:8555/udp"
volumes:
- "${FRIGATE_CONFIG_DIR:-./config}:/config"
- "${FRIGATE_MEDIA_DIR:-./media}:/media/frigate"
- /etc/localtime:/etc/localtime:ro
- /dev/bus/usb:/dev/bus/usb

View File

@ -0,0 +1,11 @@
services:
homeassistant:
image: "${HOMEASSISTANT_IMAGE:-ghcr.io/home-assistant/home-assistant:stable}"
container_name: live-homeassistant
restart: unless-stopped
network_mode: host
privileged: true
environment:
TZ: "${TZ:-UTC}"
volumes:
- "${HOMEASSISTANT_CONFIG_DIR:-./config}:/config"

View File

@ -1 +1,5 @@
data/
docker-compose.generated.yml
no-managed-policies/
*.log
*.tmp

View File

@ -10,7 +10,7 @@ export DISPLAY
prune_path() {
target="${1:-}"
[ -n "$target" ] || return 0
[ -e "$target" ] || return 0
[ -e "$target" ] || [ -L "$target" ] || return 0
rm -rf "$target" 2>/dev/null || true
}
@ -235,19 +235,19 @@ if [ "$family" = "google-chrome" ]; then
fi
render_mode="${NEKO_BROWSER_RENDER_MODE:-auto}"
render_flags="--disable-gpu --use-gl=swiftshader --enable-unsafe-swiftshader"
render_flags="--disable-gpu --disable-gpu-compositing --disable-software-rasterizer --disable-features=UseSkiaRenderer,Vulkan,VizDisplayCompositor,CanvasOopRasterization --disable-vulkan"
case "$render_mode" in
auto)
render_flags="--disable-gpu --use-gl=swiftshader --enable-unsafe-swiftshader --disable-features=UseSkiaRenderer,Vulkan --disable-vulkan"
render_flags="--disable-gpu --disable-gpu-compositing --disable-software-rasterizer --disable-features=UseSkiaRenderer,Vulkan,VizDisplayCompositor,CanvasOopRasterization --disable-vulkan --disable-zero-copy --disable-accelerated-2d-canvas --disable-accelerated-video-decode --disable-accelerated-video-encode"
;;
gpu)
render_flags=""
;;
legacy|x11|disable-gpu)
render_flags="--disable-gpu --disable-software-rasterizer --disable-features=UseSkiaRenderer"
render_flags="--disable-gpu --disable-gpu-compositing --disable-software-rasterizer --disable-features=UseSkiaRenderer,VizDisplayCompositor,CanvasOopRasterization"
;;
software|swiftshader)
render_flags="--disable-gpu --use-gl=swiftshader --enable-unsafe-swiftshader --disable-features=UseSkiaRenderer,Vulkan --disable-vulkan"
render_flags="--disable-gpu --use-gl=swiftshader --enable-unsafe-swiftshader --disable-features=UseSkiaRenderer,Vulkan,VizDisplayCompositor --disable-vulkan"
;;
esac
@ -266,6 +266,18 @@ case "${NEKO_BROWSER_PROXY:-}" in
;;
esac
extension_flags=""
case "${NEKO_LIVE_OPS_EXTENSION:-1}" in
0|false|FALSE|off|OFF|disable|disabled)
;;
*)
live_ops_extension_dir="${NEKO_LIVE_OPS_EXTENSION_DIR:-/etc/neko/live-ops-extension}"
if [ -f "$live_ops_extension_dir/manifest.json" ]; then
extension_flags="--load-extension=${live_ops_extension_dir}"
fi
;;
esac
mkdir -p "${HOME:-/home/neko}/.local/share/icons/hicolor" 2>/dev/null || true
browser_class="google-chrome"
@ -277,6 +289,7 @@ launch_browser() {
"$browser_bin" \
${render_flags} \
${proxy_flags} \
${extension_flags} \
${sandbox_flags} \
--window-position=0,0 \
--display="${DISPLAY}" \
@ -287,7 +300,6 @@ launch_browser() {
--no-first-run \
--new-window \
--start-maximized \
--force-dark-mode \
--disable-background-mode \
--disable-dev-shm-usage \
--disable-breakpad \

View File

@ -32,6 +32,8 @@ x-neko-env: &neko-env
NEKO_BROWSER_PROXY_BYPASS: "${NEKO_BROWSER_PROXY_BYPASS}"
NEKO_MANAGED_POLICIES: "${NEKO_MANAGED_POLICIES:-1}"
NEKO_TAMPERMONKEY_REPAIR: "${NEKO_TAMPERMONKEY_REPAIR:-1}"
NEKO_LIVE_OPS_EXTENSION: "${NEKO_LIVE_OPS_EXTENSION:-1}"
NEKO_LIVE_OPS_EXTENSION_DIR: "/etc/neko/live-ops-extension"
services:
neko1:
@ -57,6 +59,7 @@ services:
- "./external-extensions:/usr/share/chromium/extensions:ro"
- "./external-extensions:/usr/share/chromium-browser/extensions:ro"
- "./tampermonkey-seed:/etc/neko/tampermonkey-seed:ro"
- "./live-ops-extension:/etc/neko/live-ops-extension:ro"
- "./provisioning:/var/www/provisioning:ro"
- "./browser-launch.sh:/etc/neko/browser-launch.sh:ro"
- "./${NEKO_BROWSER_SUPERVISOR_CONF}:/etc/neko/supervisord/${NEKO_BROWSER_SUPERVISOR_CONF}:ro"
@ -84,6 +87,7 @@ services:
- "./external-extensions:/usr/share/chromium/extensions:ro"
- "./external-extensions:/usr/share/chromium-browser/extensions:ro"
- "./tampermonkey-seed:/etc/neko/tampermonkey-seed:ro"
- "./live-ops-extension:/etc/neko/live-ops-extension:ro"
- "./provisioning:/var/www/provisioning:ro"
- "./browser-launch.sh:/etc/neko/browser-launch.sh:ro"
- "./${NEKO_BROWSER_SUPERVISOR_CONF}:/etc/neko/supervisord/${NEKO_BROWSER_SUPERVISOR_CONF}:ro"
@ -111,6 +115,7 @@ services:
- "./external-extensions:/usr/share/chromium/extensions:ro"
- "./external-extensions:/usr/share/chromium-browser/extensions:ro"
- "./tampermonkey-seed:/etc/neko/tampermonkey-seed:ro"
- "./live-ops-extension:/etc/neko/live-ops-extension:ro"
- "./provisioning:/var/www/provisioning:ro"
- "./browser-launch.sh:/etc/neko/browser-launch.sh:ro"
- "./${NEKO_BROWSER_SUPERVISOR_CONF}:/etc/neko/supervisord/${NEKO_BROWSER_SUPERVISOR_CONF}:ro"

View File

@ -0,0 +1,45 @@
const API_BASES = [
"http://host.docker.internal:8001",
"http://127.0.0.1:8001",
"http://localhost:8001",
"http://10.0.0.237:8001",
];
async function postTelemetry(payload) {
const body = JSON.stringify({
...payload,
source: payload.source || "chrome_extension",
received_at: Date.now() / 1000,
});
let lastError = "";
for (const base of API_BASES) {
try {
const res = await fetch(`${base}/hub/youtube/live/ingest`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body,
cache: "no-store",
});
if (res.ok) {
const data = await res.json().catch(() => ({}));
await chrome.storage.local.set({
liveHubLastOk: Date.now(),
liveHubLastBase: base,
liveHubLastEvent: data?.event?.id || null,
});
return { ok: true, base, eventId: data?.event?.id || null };
}
lastError = `${base} HTTP ${res.status}`;
} catch (err) {
lastError = `${base} ${err?.message || String(err)}`;
}
}
await chrome.storage.local.set({ liveHubLastError: lastError, liveHubLastErrorAt: Date.now() });
return { ok: false, error: lastError };
}
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (!message || message.type !== "live-hub-youtube-telemetry") return false;
postTelemetry(message.payload || {}).then(sendResponse);
return true;
});

View File

@ -0,0 +1,159 @@
const LIVE_HUB_MIN_INTERVAL_MS = 1800;
let lastSentAt = 0;
let lastSignature = "";
function cleanText(value, max = 260) {
return String(value || "")
.replace(/\s+/g, " ")
.trim()
.slice(0, max);
}
function pageText() {
return cleanText(document.body?.innerText || "", 6000);
}
function parseCompactNumber(raw) {
const text = cleanText(raw, 40).replace(/,/g, "");
const match = text.match(/(\d+(?:\.\d+)?)([kKmMwW万]*)/);
if (!match) return null;
let value = Number(match[1]);
const unit = match[2].toLowerCase();
if (unit === "k") value *= 1000;
if (unit === "m") value *= 1000000;
if (unit === "w" || unit === "万") value *= 10000;
return Number.isFinite(value) ? Math.round(value) : null;
}
function firstNumberByPatterns(text, patterns) {
for (const pattern of patterns) {
const match = text.match(pattern);
if (match) {
const parsed = parseCompactNumber(match[1]);
if (parsed != null) return parsed;
}
}
return null;
}
function detectLiveStatus(text) {
const lower = text.toLowerCase();
if (/stream ended|not live|offline|直播已结束|未在直播/.test(lower)) return "ended";
if (/you'?re live|streaming|excellent connection|stream is healthy|直播中|正在直播|已开始直播/.test(lower)) return "live";
if (/waiting|preview|scheduled|等待|预定|未开始/.test(lower)) return "waiting";
if (/error|failed|copyright|policy|异常|错误|受限|违规/.test(lower)) return "attention";
return "";
}
function detectHealth(text) {
const lower = text.toLowerCase();
if (/excellent connection|stream is healthy|health excellent|连接状况极佳|状况良好/.test(lower)) return "excellent";
if (/good connection|healthy|良好/.test(lower)) return "good";
if (/unstable|poor|buffer|warning|警告|不稳定|不佳|卡顿/.test(lower)) return "warning";
if (/error|failed|disconnect|异常|错误|断开/.test(lower)) return "error";
return "";
}
function collectPopupTexts() {
const selectors = [
"[role='dialog']",
"[aria-live='assertive']",
"[aria-live='polite']",
"ytcp-toast",
"tp-yt-paper-toast",
"paper-dialog",
"ytcp-alert",
"ytcp-ve",
];
const out = [];
for (const node of document.querySelectorAll(selectors.join(","))) {
const rect = node.getBoundingClientRect?.();
if (rect && rect.width === 0 && rect.height === 0) continue;
const text = cleanText(node.innerText || node.textContent || "", 500);
if (text && !out.includes(text)) out.push(text);
if (out.length >= 8) break;
}
return out;
}
function collectStreamTitle() {
const selectors = [
"input[aria-label*='Title']",
"textarea[aria-label*='Title']",
"ytcp-social-suggestions-textbox",
"ytcp-video-title",
"h1",
];
for (const selector of selectors) {
const node = document.querySelector(selector);
const value = node?.value || node?.innerText || node?.textContent;
const text = cleanText(value, 180);
if (text) return text;
}
return cleanText(document.title, 180);
}
function collectTelemetry() {
const text = pageText();
const viewerCount = firstNumberByPatterns(text, [
/([\d,.]+[kKmMwW万]?)\s*(?:watching|viewers|concurrent viewers)/i,
/([\d,.]+[kKmMwW万]?)\s*(?:人正在观看|正在观看|观看|在线)/,
]);
const likeCount = firstNumberByPatterns(text, [
/([\d,.]+[kKmMwW万]?)\s*(?:likes|like count)/i,
/([\d,.]+[kKmMwW万]?)\s*(?:点赞|赞)/,
]);
const popups = collectPopupTexts();
const payload = {
captured_at: Date.now() / 1000,
source: "chrome_extension",
url: location.href,
page_title: document.title,
stream_title: collectStreamTitle(),
live_status: detectLiveStatus(text),
health: detectHealth(text),
viewer_count: viewerCount,
like_count: likeCount,
popups,
text: text.slice(0, 2200),
signals: {
has_dialog: popups.length > 0,
visibility: document.visibilityState,
focused: document.hasFocus(),
path: location.pathname,
},
};
return payload;
}
function signatureOf(payload) {
return JSON.stringify([
payload.url,
payload.live_status,
payload.health,
payload.viewer_count,
payload.like_count,
payload.popups,
payload.stream_title,
]);
}
function sendTelemetry(force = false) {
const now = Date.now();
if (!force && now - lastSentAt < LIVE_HUB_MIN_INTERVAL_MS) return;
const payload = collectTelemetry();
const sig = signatureOf(payload);
if (!force && sig === lastSignature && now - lastSentAt < 10000) return;
lastSentAt = now;
lastSignature = sig;
chrome.runtime.sendMessage({ type: "live-hub-youtube-telemetry", payload }, () => {
void chrome.runtime.lastError;
});
}
const observer = new MutationObserver(() => sendTelemetry(false));
observer.observe(document.documentElement, { subtree: true, childList: true, characterData: true });
window.addEventListener("focus", () => sendTelemetry(true));
document.addEventListener("visibilitychange", () => sendTelemetry(true));
setInterval(() => sendTelemetry(false), 3000);
sendTelemetry(true);

View File

@ -0,0 +1,29 @@
{
"manifest_version": 3,
"name": "Live Hub YouTube Studio Telemetry",
"version": "1.0.0",
"description": "Captures YouTube Studio live status, viewer signals, stream health, and popups for the LAN Live Hub.",
"permissions": ["storage"],
"host_permissions": [
"https://studio.youtube.com/*",
"https://www.youtube.com/*",
"http://host.docker.internal:8001/*",
"http://127.0.0.1:8001/*",
"http://localhost:8001/*",
"http://10.0.0.237:8001/*"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": [
"https://studio.youtube.com/*",
"https://www.youtube.com/live_dashboard*",
"https://www.youtube.com/watch*"
],
"js": ["content.js"],
"run_at": "document_idle"
}
]
}

View File

@ -0,0 +1,5 @@
base-url: "http://live.local:8089"
listen-http: ":80"
cache-file: "/var/cache/ntfy/cache.db"
attachment-cache-dir: "/var/cache/ntfy/attachments"
auth-default-access: "read-write"

View File

@ -0,0 +1,13 @@
services:
ntfy:
image: "${NTFY_IMAGE:-binwiederhier/ntfy:latest}"
container_name: live-ntfy
restart: unless-stopped
command: serve
environment:
TZ: "${TZ:-UTC}"
ports:
- "${NTFY_PORT:-8089}:80"
volumes:
- "${NTFY_CONFIG_DIR:-./config}:/etc/ntfy"
- "${NTFY_CACHE_DIR:-./cache}:/var/cache/ntfy"

View File

@ -31,10 +31,9 @@ def _read_text(path: Path) -> str:
def _raise_write_permission_error(path: Path, exc: OSError) -> None:
raise PermissionError(
f"Permission denied: {path} is not writable by the current web service user. "
"Fix deployment ownership for runtime dirs such as config/logs/backup_config/.pm2/.process_runner/"
"downloads/backup, and grant the web user group write access to ShellCrash managed roots under "
"/etc/ShellCrash/{yamls,configs,jsons}."
f"Runtime path is not writable yet: {path}. "
"Run the live stack install/refresh script once so it can repair config/logs/backup_config/.pm2/"
".process_runner/downloads/backup and service directories to all-user read/write/execute access."
) from exc
@ -339,7 +338,7 @@ def _analyze_youtube_ini(content: str) -> dict[str, Any]:
key = parser.get(section, "key", fallback="").strip() if parser.has_section(section) else ""
rtmps = parser.get(section, "rtmps", fallback="是").strip()
bitrate = parser.get(section, "bitrate", fallback="").strip()
fast_audio = parser.get(section, "fast_audio", fallback="0").strip()
fast_audio = parser.get(section, "fast_audio", fallback="1").strip()
if not key:
issues.append(_issue("error", "missing_stream_key", "YouTube stream key is empty."))
@ -356,7 +355,7 @@ def _analyze_youtube_ini(content: str) -> dict[str, Any]:
_stat("stream_key", "Stream key", "configured" if key else "missing"),
_stat("rtmps", "RTMPS", rtmps or "是"),
_stat("bitrate", "Bitrate", bitrate or "auto"),
_stat("fast_audio", "fast_audio", fast_audio or "0"),
_stat("fast_audio", "fast_audio", fast_audio or "1"),
]
)
summary = "YouTube relay settings analyzed."

View File

@ -63,6 +63,8 @@ class ManagedRoot:
if _PRO_URL_CONFIG_INI.match(n) or _PRO_YOUTUBE_INI.match(n):
return True
return False
if "*" in self.allowed_suffixes:
return True
return rel_path.suffix.lower() in self.allowed_suffixes
@ -105,6 +107,11 @@ SERVICE_SPECS: tuple[ServiceSpec, ...] = (
ServiceSpec("pulseaudio", "PulseAudio", "media", "Audio bridge for browser and Android media"),
ServiceSpec("kmscube", "kmscube", "media", "DRM/KMS diagnostics for HDMI rendering"),
ServiceSpec("openclaw", "OpenClaw", "automation", "Automation gateway and web workspace"),
ServiceSpec("homeassistant", "Home Assistant", "studio", "Local smart-home automation workspace"),
ServiceSpec("frigate", "Frigate NVR", "studio", "Camera NVR with object detection and RTSP/WebRTC access"),
ServiceSpec("wol", "WOL 网络唤醒", "studio", "Wake-on-LAN packet sender for LAN devices"),
ServiceSpec("ntfy", "ntfy", "studio", "LAN notification topic server"),
ServiceSpec("coturn", "coturn TURN", "network", "TURN relay for Neko and Frigate WebRTC remote access"),
ServiceSpec(
"android_gateway",
"Android Gateway",
@ -128,7 +135,7 @@ def managed_roots() -> dict[str, ManagedRoot]:
description="Core livestream app configuration files",
path=CONFIG_DIR,
allow_create=True,
allow_delete=False,
allow_delete=True,
explicit_names=(
"config.ini",
"youtube.ini",
@ -144,7 +151,7 @@ def managed_roots() -> dict[str, ManagedRoot]:
description="Ports, feature toggles, hostname, Wi-Fi, and gateway settings",
path=CONFIG_DIR,
allow_create=True,
allow_delete=False,
allow_delete=True,
explicit_names=("system-stack.env", "system-stack.env.example"),
default_file="system-stack.env",
),
@ -200,6 +207,39 @@ def managed_roots() -> dict[str, ManagedRoot]:
allowed_suffixes=(".yaml", ".yml", ".json"),
default_file="services.yaml",
),
"homeassistant-config": ManagedRoot(
root_id="homeassistant-config",
label="Home Assistant Config",
description="Home Assistant configuration files",
path=Path(os.environ.get("HOMEASSISTANT_CONFIG_DIR", "/var/lib/live-homeassistant/config")),
allow_create=True,
allow_delete=True,
recursive=True,
allowed_suffixes=("*",),
default_file="configuration.yaml",
),
"frigate-config": ManagedRoot(
root_id="frigate-config",
label="Frigate Config",
description="Frigate NVR configuration files",
path=Path(os.environ.get("FRIGATE_CONFIG_DIR", "/var/lib/live-frigate/config")),
allow_create=True,
allow_delete=True,
recursive=True,
allowed_suffixes=("*",),
default_file="config.yml",
),
"ntfy-config": ManagedRoot(
root_id="ntfy-config",
label="ntfy Config",
description="ntfy notification server configuration files",
path=Path(os.environ.get("NTFY_CONFIG_DIR", "/var/lib/live-ntfy/config")),
allow_create=True,
allow_delete=True,
recursive=True,
allowed_suffixes=("*",),
default_file="server.yml",
),
}
@ -429,11 +469,6 @@ async def apply_shellcrash_profile(
if not SERVICE_CTL.is_file():
raise RuntimeError("Service controller script is missing")
if hasattr(os, "geteuid") and os.geteuid() == 0:
code, output = await _run_command(cmd, timeout=180.0)
elif shutil.which("sudo"):
code, output = await _run_command(["sudo", "-n", *cmd], timeout=180.0)
else:
code, output = await _run_command(cmd, timeout=180.0)
info = _parse_kv_output(output)
@ -463,11 +498,6 @@ async def ensure_shellcrash_web_panel() -> dict:
raise RuntimeError("Service controller script is missing")
cmd = [BASH_BIN, str(SERVICE_CTL), "shellcrash", "web_panel"]
if hasattr(os, "geteuid") and os.geteuid() == 0:
code, output = await _run_command(cmd, timeout=180.0)
elif shutil.which("sudo"):
code, output = await _run_command(["sudo", "-n", *cmd], timeout=180.0)
else:
code, output = await _run_command(cmd, timeout=180.0)
info = _parse_kv_output(output)
@ -569,8 +599,6 @@ async def service_action(service_id: str, action: str) -> dict:
cmd = [BASH_BIN, str(SERVICE_CTL), service_id, action]
code, output = await _run_command(cmd, timeout=45.0)
if code != 0 and shutil.which("sudo"):
code, output = await _run_command(["sudo", "-n", *cmd], timeout=45.0)
info = _parse_kv_output(output)
message = info.get("message", output)
if code != 0:
@ -585,6 +613,131 @@ async def service_action(service_id: str, action: str) -> dict:
return status
def _neko_configured_instance_count() -> int:
return len(_neko_http_ports(load_stack_env()))
def _neko_container_name(instance_id: int) -> str:
return f"live-neko-{instance_id}"
async def _neko_container_state(container: str) -> dict[str, Any]:
code, output = await _run_command(
["docker", "inspect", "--format", "{{.State.Status}}", container],
timeout=10.0,
)
detail = (output or "").strip()
if code != 0:
low = detail.lower()
missing = any(token in low for token in ("no such object", "no such container", "not found"))
return {
"exists": False,
"running": False,
"status": "missing" if missing else "error",
"detail": detail,
}
status = (detail.splitlines()[-1] if detail else "unknown").strip().lower()
return {
"exists": True,
"running": status == "running",
"status": status or "unknown",
"detail": detail,
}
def _neko_status_message(instance_id: int, state: dict[str, Any]) -> str:
if not state.get("exists"):
return f"Neko {instance_id} 容器不存在"
if state.get("running"):
return f"Neko {instance_id} 正在运行"
return f"Neko {instance_id} 已停止"
async def neko_instance_action(instance_id: int, action: str) -> dict[str, Any]:
action = action.strip().lower()
if action not in {"status", "start", "stop", "restart", "delete"}:
raise ValueError(f"Unsupported Neko action: {action}")
configured_count = _neko_configured_instance_count()
if instance_id < 1 or instance_id > configured_count:
raise ValueError(f"Neko instance must be between 1 and {configured_count}")
if not shutil.which("docker"):
raise RuntimeError("Docker 不可用,无法控制 Neko 容器")
container = _neko_container_name(instance_id)
before = await _neko_container_state(container)
message = _neko_status_message(instance_id, before)
detail = str(before.get("detail") or "")
if action == "start":
if before.get("running"):
message = f"Neko {instance_id} 已经在运行"
elif before.get("exists"):
code, output = await _run_command(["docker", "start", container], timeout=45.0)
if code != 0:
raise RuntimeError(f"Neko {instance_id} 启动失败:{output or 'docker start failed'}")
message = f"Neko {instance_id} 已启动"
detail = output
else:
if not SERVICE_CTL.is_file():
raise RuntimeError("Neko 容器不存在,且服务控制脚本缺失,无法重建")
code, output = await _run_command([BASH_BIN, str(SERVICE_CTL), "neko", "start"], timeout=120.0)
if code != 0:
raise RuntimeError(f"Neko {instance_id} 容器不存在,重建失败:{output or 'neko start failed'}")
message = f"Neko {instance_id} 容器不存在,已重建并启动"
detail = output
elif action == "stop":
if not before.get("exists"):
message = f"Neko {instance_id} 容器不存在,无需停止"
elif not before.get("running"):
message = f"Neko {instance_id} 已经停止"
else:
code, output = await _run_command(["docker", "stop", "-t", "10", container], timeout=45.0)
if code != 0:
raise RuntimeError(f"Neko {instance_id} 停止失败:{output or 'docker stop failed'}")
message = f"Neko {instance_id} 已停止"
detail = output
elif action == "restart":
if before.get("exists"):
code, output = await _run_command(["docker", "restart", container], timeout=60.0)
if code != 0:
raise RuntimeError(f"Neko {instance_id} 重启失败:{output or 'docker restart failed'}")
message = f"Neko {instance_id} 已重启"
detail = output
else:
if not SERVICE_CTL.is_file():
raise RuntimeError("Neko 容器不存在,且服务控制脚本缺失,无法重建")
code, output = await _run_command([BASH_BIN, str(SERVICE_CTL), "neko", "start"], timeout=120.0)
if code != 0:
raise RuntimeError(f"Neko {instance_id} 容器不存在,重建失败:{output or 'neko start failed'}")
message = f"Neko {instance_id} 容器不存在,已重建并启动"
detail = output
elif action == "delete":
if not before.get("exists"):
message = f"Neko {instance_id} 容器已不存在"
else:
code, output = await _run_command(["docker", "rm", "-f", container], timeout=45.0)
if code != 0:
raise RuntimeError(f"Neko {instance_id} 删除失败:{output or 'docker rm failed'}")
message = f"Neko {instance_id} 容器已删除,浏览器配置数据已保留"
detail = output
after = await _neko_container_state(container)
return {
"service_id": "neko",
"id": instance_id,
"container": container,
"configured_count": configured_count,
"action": action,
"available": True,
"exists": bool(after.get("exists")),
"running": bool(after.get("running")),
"status": str(after.get("status") or "unknown"),
"message": message,
"detail": detail or str(after.get("detail") or ""),
"profile_preserved": True,
}
def local_ips() -> list[str]:
ips: list[str] = []
if shutil.which("ip"):
@ -684,6 +837,8 @@ def _split_host_list(*values: str | None) -> list[str]:
def _neko_access_hosts(env: dict[str, str], lan_ips: list[str]) -> list[dict[str, str]]:
hosts: list[dict[str, str]] = []
access_mode = str(env.get("NEKO_ACCESS_MODE") or "lan").strip().lower()
remote_mode = access_mode in {"remote", "wg", "wireguard", "wan"}
def add(kind: str, label: str, host: str) -> None:
if not host or any(item["host"] == host and item["kind"] == kind for item in hosts):
@ -692,6 +847,8 @@ def _neko_access_hosts(env: dict[str, str], lan_ips: list[str]) -> list[dict[str
for ip in lan_ips:
add("lan", "LAN", ip)
nat1to1 = str(env.get("NEKO_WEBRTC_NAT1TO1") or "").strip()
if remote_mode:
for host in _split_host_list(
env.get("NEKO_WIREGUARD_HOSTS"),
env.get("NEKO_WIREGUARD_HOST"),
@ -699,10 +856,10 @@ def _neko_access_hosts(env: dict[str, str], lan_ips: list[str]) -> list[dict[str
env.get("WIREGUARD_HOST"),
):
add("wireguard", "WireGuard", host)
nat1to1 = str(env.get("NEKO_WEBRTC_NAT1TO1") or "").strip()
if nat1to1 and not any(item["host"] == nat1to1 for item in hosts):
label = "WireGuard" if nat1to1.startswith(("10.", "172.", "192.168.")) else "NAT1TO1"
add("wireguard" if label == "WireGuard" else "nat1to1", label, nat1to1)
add("wireguard", "WireGuard", nat1to1)
elif nat1to1 and nat1to1 in lan_ips and not any(item["host"] == nat1to1 for item in hosts):
add("lan", "LAN", nat1to1)
for host in _split_host_list(env.get("NEKO_PUBLIC_HOSTS"), env.get("NEKO_PUBLIC_HOST")):
add("public", "Public", host)
return hosts
@ -1180,6 +1337,11 @@ def stack_summary() -> dict:
vscode_port = env.get("VSCODE_SERVER_PORT", "8440")
uptime_kuma_port = env.get("UPTIME_KUMA_PORT", "3001")
openclaw_port = env.get("OPENCLAW_GATEWAY_PORT", "18789")
homeassistant_port = env.get("HOMEASSISTANT_PORT", "8123")
frigate_web_port = env.get("FRIGATE_WEB_PORT", "5001")
ntfy_port = env.get("NTFY_PORT", "8089")
coturn_port = env.get("COTURN_PORT", "3478")
coturn_tls_port = env.get("COTURN_TLS_PORT", "5349")
pulseaudio_port = env.get("PULSEAUDIO_TCP_PORT", "4713")
ql: dict[str, str] = {
"control_plane": control_url,
@ -1199,6 +1361,14 @@ def stack_summary() -> dict:
"pulseaudio_tcp": f"{mdns_host}:{pulseaudio_port}",
"openclaw": f"http://{mdns_host}:{openclaw_port}",
"services_console": f"{control_url}/?view=services",
"studio": f"{control_url}/?view=studio",
"youtube_events": f"{control_url}/youtube-events",
"homeassistant": f"http://{mdns_host}:{homeassistant_port}",
"frigate": f"http://{mdns_host}:{frigate_web_port}",
"ntfy": f"http://{mdns_host}:{ntfy_port}",
"coturn_turn": f"turn:{mdns_host}:{coturn_port}?transport=udp",
"coturn_turns": f"turns:{mdns_host}:{coturn_tls_port}?transport=tcp",
"wol": f"{control_url}/?view=studio",
}
for instance in neko_instances:
quick_link_key = str(instance["quick_link_key"])

View File

@ -0,0 +1,77 @@
from __future__ import annotations
import re
from typing import Any
_DOUYIN_LIVE_URL_RE = re.compile(r"https?://(?:www\.)?live\.douyin\.com/([a-zA-Z0-9_-]+)", re.IGNORECASE)
_STATUS_TITLE_RE = re.compile(
r"(?:序号\s*\d+\s*)?(.{1,80}?)\s*(?:等待直播|正在直播|直播中|已开播|开始推流|主播已下播|下播|录制中|推流中)",
re.IGNORECASE,
)
_LABEL_TITLE_RE = re.compile(r"(?:主播|房间名|直播间|抖音源|源站|标题)\s*[::]\s*(.{1,80})", re.IGNORECASE)
_BAD_TITLE_RE = re.compile(r"^\s*(?:-|—|_|无|未知|unknown|null|undefined|none|nan)?\s*$", re.IGNORECASE)
def _clean_source_title(value: str) -> str:
text = (value or "").strip().strip("\"'`[]()()【】")
text = re.sub(r"^(?:主播|房间名|直播间|抖音源|源站|标题)\s*[::]\s*", "", text, flags=re.IGNORECASE)
text = _DOUYIN_LIVE_URL_RE.sub("", text)
text = re.sub(r"(?:等待直播|正在直播|直播中|已开播|开始推流|主播已下播|下播|录制中|推流中).*$", "", text).strip()
text = text.strip(" ,,;;||-—::")
if _BAD_TITLE_RE.match(text):
return ""
if "live.douyin.com" in text.lower():
return ""
if re.fullmatch(r"\d{5,}", text):
return ""
if text.startswith(("监测", "格式", "错误", "无录制任务")):
return ""
return text[:48]
def _source_title_from_url_lines(url_lines: str) -> str:
for line in (url_lines or "").splitlines():
raw = line.strip()
if not raw or raw.startswith("#"):
continue
match = _DOUYIN_LIVE_URL_RE.search(raw)
if not match:
continue
tail = raw[match.end() :].strip(" ,,;;||-—::")
title = _clean_source_title(tail)
if title:
return title
parts = re.split(r"[,,||]", raw, maxsplit=1)
if len(parts) > 1:
title = _clean_source_title(parts[1])
if title:
return title
return ""
def _source_title_from_log(recent_log: str) -> str:
lines = [line.strip() for line in (recent_log or "").splitlines() if line.strip()]
for line in reversed(lines[-160:]):
for pattern in (_LABEL_TITLE_RE, _STATUS_TITLE_RE):
match = pattern.search(line)
if not match:
continue
title = _clean_source_title(match.group(1))
if title:
return title
return ""
def extract_douyin_source_meta(url_lines: str = "", recent_log: str = "") -> dict[str, Any]:
text = f"{url_lines or ''}\n{recent_log or ''}"
room_match = _DOUYIN_LIVE_URL_RE.search(text)
room_id = room_match.group(1) if room_match else ""
source_url = f"https://live.douyin.com/{room_id}" if room_id else ""
title = _source_title_from_url_lines(url_lines) or _source_title_from_log(recent_log)
display = title or (f"抖音直播间 {room_id}" if room_id else "")
return {
"source_title": title,
"source_room_id": room_id,
"source_url": source_url,
"source_display": display,
}

View File

@ -9,7 +9,7 @@ from pathlib import Path
from typing import Any
from src.control_plane import CONFIG_DIR
from src.youtube_pro_runtime import normalize_youtube_pro_channels
from src.youtube_pro_runtime import channel_pm2_name, normalize_youtube_pro_channels
_DB_NAME = "hub_state.sqlite"
_KEY_YOUTUBE_PRO = "youtube_pro_channels_v1"
@ -116,3 +116,37 @@ def set_youtube_pro_channels(channels: list[dict[str, Any]]) -> None:
raise
_repair_permissions_best_effort()
_write_youtube_pro_channels(raw, ts)
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."""
incoming = normalize_youtube_pro_channels(channels)
existing = get_youtube_pro_channels()
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()
if pm2 and pm2 not in seen_pm2 and cid not in seen_ids:
merged.append(dict(row))
merged = normalize_youtube_pro_channels(merged)
set_youtube_pro_channels(merged)
return merged

View File

@ -21,12 +21,15 @@ from src.control_plane import (
stack_summary,
system_snapshot,
)
from src.douyin_source_display import extract_douyin_source_meta
from src.live_config import business_config, load_hub_config_snapshot, services_config_list
from src.process_runtime_status import coerce_declared_process_status, summarize_process_activity
from src.web_process_backend import WebProcessBackend
from src.youtube_config_paths import resolve_youtube_style_config_paths
from src.wireguard_config import (
WireGuardConfigError,
apply_wireguard_config,
configure_neko_wireguard_access,
read_imported_wireguard_config,
save_imported_wireguard_config,
wireguard_runtime_status,
@ -36,6 +39,13 @@ from src.redroid_control import redroid_runtime_summary
from src.hdmi_control import hdmi_capture_summary
from src.neko_capacity import ensure_neko_capacity_for_youtube_channels
from src.youtube_pro_runtime import normalize_youtube_pro_channels
from src.youtube_live_store import (
close_live_event,
get_live_event,
ingest_browser_telemetry,
list_live_events,
youtube_live_summary,
)
router = APIRouter(prefix="/hub", tags=["无人直播系统"])
@ -105,6 +115,23 @@ def _tail_file_text(path: str | None, max_lines: int, max_age_seconds: int | Non
return "\n".join(lines)
def _is_youtube_monitor_entry(entry: dict[str, Any]) -> bool:
script = str(entry.get("script") or "").strip()
pm2 = str(entry.get("pm2") or "").strip().lower()
stem = Path(script).stem.lower() if script else ""
return stem.startswith("youtube") or stem.startswith("douyin_youtube") or pm2.startswith("youtube2__")
def _youtube_url_lines_for_process(name: str) -> str:
if _repo_root is None:
return ""
try:
_, url_path = resolve_youtube_style_config_paths(_repo_root, name)
return url_path.read_text(encoding="utf-8", errors="ignore") if url_path.is_file() else ""
except OSError:
return ""
def _newest_log_age_seconds(*paths: str | None) -> float | None:
newest_mtime: float | None = None
for path in paths:
@ -141,6 +168,7 @@ class BusinessDouyinPatch(BaseModel):
class YoutubeProChannelsBody(BaseModel):
channels: list[dict[str, Any]] = Field(default_factory=list)
force: bool = False
@field_validator("channels", mode="after")
@classmethod
@ -157,6 +185,15 @@ class WireGuardImportBody(BaseModel):
apply: Optional[bool] = False
class WireGuardNekoAccessBody(BaseModel):
mode: str = Field(default="lan", pattern="^(lan|remote)$")
restart: bool = True
class YoutubeLiveCloseBody(BaseModel):
reason: str = Field(default="manual", max_length=200)
@router.get("/dashboard")
async def hub_dashboard() -> dict[str, Any]:
snap = system_snapshot()
@ -209,12 +246,18 @@ async def hub_dashboard() -> dict[str, Any]:
log_age_seconds=_newest_log_age_seconds(info.get("out_path"), info.get("err_path")),
ffmpeg_pids=ffmpeg_pids,
)
source_meta = (
extract_douyin_source_meta(_youtube_url_lines_for_process(name), recent_log)
if _is_youtube_monitor_entry(entry)
else {}
)
return {
"pm2": name,
"label": entry.get("label", name),
"script": entry.get("script", ""),
**info,
**activity,
**source_meta,
}
results = await asyncio.gather(*(build_live_row(entry) for entry in entries), return_exceptions=True)
@ -293,6 +336,16 @@ async def hub_network_wireguard_save(body: WireGuardImportBody) -> dict[str, Any
repo_root=repo_root,
route_mode=body.route_mode or "overlay",
)
status = result.get("status") if isinstance(result.get("status"), dict) else None
access = (status or {}).get("neko_access") if isinstance((status or {}).get("neko_access"), dict) else None
if access and access.get("mode") == "remote":
result["neko_access"] = await asyncio.to_thread(
configure_neko_wireguard_access,
repo_root=repo_root,
mode="remote",
restart=True,
status=status,
)
else:
result = await asyncio.to_thread(
save_imported_wireguard_config,
@ -321,6 +374,21 @@ async def hub_network_wireguard_status() -> dict[str, Any]:
return {"wireguard": status}
@router.post("/network/wireguard/neko_access")
async def hub_network_wireguard_neko_access(body: WireGuardNekoAccessBody) -> dict[str, Any]:
repo_root = _repo_root or Path.cwd()
try:
access = await asyncio.to_thread(
configure_neko_wireguard_access,
repo_root=repo_root,
mode=body.mode,
restart=body.restart,
)
except WireGuardConfigError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return {"message": "ok", "neko_access": access}
@router.get("/network/wireguard/config/{name}")
async def hub_network_wireguard_config(name: str) -> dict[str, Any]:
repo_root = _repo_root or Path.cwd()
@ -339,10 +407,14 @@ async def hub_youtube_pro_channels_read() -> dict[str, Any]:
@router.post("/youtube_pro_channels")
async def hub_youtube_pro_channels_write(body: YoutubeProChannelsBody) -> dict[str, Any]:
from src.hub_kv_store import set_youtube_pro_channels
from src.hub_kv_store import get_youtube_pro_channels, merge_youtube_pro_channels, set_youtube_pro_channels
try:
if body.force:
set_youtube_pro_channels(body.channels)
channels = get_youtube_pro_channels()
else:
channels = merge_youtube_pro_channels(body.channels)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except sqlite3.Error as exc:
@ -350,8 +422,50 @@ async def hub_youtube_pro_channels_write(body: YoutubeProChannelsBody) -> dict[s
status_code=500,
detail=f"多频道状态数据库写入失败: {exc}; 请确认 config 目录归 live 用户可写",
) from exc
capacity = await asyncio.to_thread(ensure_neko_capacity_for_youtube_channels, _repo_root, body.channels)
return {"message": "ok", "neko": capacity}
capacity = await asyncio.to_thread(ensure_neko_capacity_for_youtube_channels, _repo_root, channels)
return {"message": "ok", "channels": channels, "neko": capacity}
@router.get("/youtube/live/summary")
async def hub_youtube_live_summary() -> dict[str, Any]:
return await asyncio.to_thread(youtube_live_summary)
@router.get("/youtube/live/events")
async def hub_youtube_live_events(
status: str = "",
process: str = "",
limit: int = 50,
offset: int = 0,
) -> dict[str, Any]:
return await asyncio.to_thread(
list_live_events,
status=status,
process=process,
limit=limit,
offset=offset,
)
@router.get("/youtube/live/events/{event_id}")
async def hub_youtube_live_event_detail(event_id: str) -> dict[str, Any]:
event = await asyncio.to_thread(get_live_event, event_id)
if not event:
raise HTTPException(status_code=404, detail="live event not found")
return {"event": event}
@router.post("/youtube/live/events/{event_id}/close")
async def hub_youtube_live_event_close(event_id: str, body: YoutubeLiveCloseBody) -> dict[str, Any]:
result = await asyncio.to_thread(close_live_event, event_id, reason=body.reason)
if not result:
raise HTTPException(status_code=404, detail="live event not found")
return result
@router.post("/youtube/live/ingest")
async def hub_youtube_live_ingest(payload: dict[str, Any]) -> dict[str, Any]:
return await asyncio.to_thread(ingest_browser_telemetry, payload)
@router.get("/services/declared")

View File

@ -3,6 +3,7 @@ from __future__ import annotations
import os
import platform
import shutil
import socket
import subprocess
import time
@ -13,7 +14,25 @@ from typing import Any
GOOGLE_204 = "https://www.google.com/generate_204"
YOUTUBE_204 = "https://www.youtube.com/generate_204"
DOUYIN_LIVE = "https://live.douyin.com/"
DEFAULT_TIMEOUT_SECONDS = 5
PROXY_ENV_KEYS = (
"http_proxy",
"https_proxy",
"all_proxy",
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
"no_proxy",
"NO_PROXY",
)
PROBE_TARGETS: tuple[dict[str, Any], ...] = (
{"id": "google", "label": "Google", "url": GOOGLE_204, "role": "global", "accept_status_max": 399},
{"id": "youtube", "label": "YouTube", "url": YOUTUBE_204, "role": "global", "accept_status_max": 399},
{"id": "douyin", "label": "Douyin Live", "url": DOUYIN_LIVE, "role": "source", "accept_status_max": 499},
)
def _run(args: list[str], *, timeout: float = 4.0) -> tuple[int, str]:
@ -43,6 +62,17 @@ def _read_shellcrash_cfg() -> dict[str, str]:
return out
def shellcrash_config_status() -> dict[str, Any]:
base = Path(os.environ.get("SHELLCRASH_DIR", "/etc/ShellCrash"))
for path in (base / "yamls" / "config.yaml", Path("/tmp/ShellCrash/config.yaml")):
try:
if path.is_file() and path.stat().st_size > 0:
return {"available": True, "path": str(path), "bytes": path.stat().st_size}
except OSError:
continue
return {"available": False, "path": "", "bytes": 0}
def shellcrash_runtime() -> dict[str, Any]:
cfg = _read_shellcrash_cfg()
code, active = _run(["systemctl", "is-active", "shellcrash.service"], timeout=2.0)
@ -58,7 +88,70 @@ def shellcrash_runtime() -> dict[str, Any]:
}
def _probe_url(url: str, *, proxy: str | None = None, timeout: int = DEFAULT_TIMEOUT_SECONDS) -> dict[str, Any]:
def _env_flag(name: str, default: bool = False) -> bool:
raw = os.environ.get(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "on", "enable", "enabled"}
def _unit_exists(unit: str) -> bool:
code, output = _run(["systemctl", "list-unit-files", unit, "--no-legend"], timeout=2.0)
return code == 0 and unit in output
def _stage_shellcrash_runtime_config(config_path: str) -> None:
src = Path(config_path)
if not src.is_file():
return
dst = Path("/tmp/ShellCrash/config.yaml")
try:
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src, dst)
dst.chmod(0o644)
except OSError:
return
def autostart_shellcrash_if_configured() -> dict[str, Any]:
if not _env_flag("SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL", True):
return {"attempted": False, "started": False, "reason": "disabled"}
cfg = shellcrash_config_status()
if not cfg.get("available"):
return {"attempted": False, "started": False, "reason": "missing_config", "config": cfg}
_stage_shellcrash_runtime_config(str(cfg.get("path") or ""))
command: list[str] | None = None
if _unit_exists("shellcrash.service"):
_run(["systemctl", "reset-failed", "shellcrash.service"], timeout=3.0)
command = ["systemctl", "enable", "--now", "shellcrash.service"]
else:
start = Path(os.environ.get("SHELLCRASH_DIR", "/etc/ShellCrash")) / "start.sh"
if start.is_file():
command = [str(start), "start"]
if not command:
return {"attempted": False, "started": False, "reason": "missing_launcher", "config": cfg}
code, output = _run(command, timeout=15.0)
if code == 0:
time.sleep(1.0)
shell = shellcrash_runtime()
return {
"attempted": True,
"started": bool(shell.get("running")),
"code": code,
"output": output,
"command": " ".join(command),
"config": cfg,
"shellcrash": shell,
}
def _probe_url(
url: str,
*,
proxy: str | None = None,
timeout: int = DEFAULT_TIMEOUT_SECONDS,
accept_status_max: int = 399,
) -> dict[str, Any]:
handlers: list[urllib.request.BaseHandler] = []
if proxy:
handlers.append(urllib.request.ProxyHandler({"http": proxy, "https": proxy}))
@ -80,7 +173,7 @@ def _probe_url(url: str, *, proxy: str | None = None, timeout: int = DEFAULT_TIM
"error": str(exc),
}
return {
"ok": 200 <= status < 400,
"ok": 200 <= status <= accept_status_max,
"url": url,
"proxy": proxy or "",
"elapsed_ms": int((time.monotonic() - started) * 1000),
@ -88,8 +181,27 @@ def _probe_url(url: str, *, proxy: str | None = None, timeout: int = DEFAULT_TIM
}
def _probe_pair(proxy: str | None) -> list[dict[str, Any]]:
return [_probe_url(GOOGLE_204, proxy=proxy), _probe_url(YOUTUBE_204, proxy=proxy)]
def _probe_targets(proxy: str | None) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
for target in PROBE_TARGETS:
row = _probe_url(
str(target["url"]),
proxy=proxy,
accept_status_max=int(target.get("accept_status_max") or 399),
)
row["target"] = target["id"]
row["label"] = target["label"]
row["role"] = target["role"]
out.append(row)
return out
def _global_ok(probes: list[dict[str, Any]]) -> bool:
return any(item.get("ok") for item in probes if item.get("role") == "global")
def _douyin_ok(probes: list[dict[str, Any]]) -> bool:
return any(item.get("ok") for item in probes if item.get("target") == "douyin")
def _proxy_env(proxy: str) -> dict[str, str]:
@ -102,6 +214,11 @@ def _proxy_env(proxy: str) -> dict[str, str]:
"172.16.0.0/12",
"192.168.0.0/16",
"100.64.0.0/10",
"douyin.com",
".douyin.com",
"*.douyin.com",
"live.douyin.com",
"v.douyin.com",
"*.local",
]
)
@ -124,39 +241,116 @@ def apply_process_proxy_env(env: dict[str, str]) -> None:
os.environ[key] = value
def clear_process_proxy_env(*, mode: str = "direct") -> None:
for key in PROXY_ENV_KEYS:
os.environ.pop(key, None)
os.environ["LIVE_YOUTUBE_NETWORK_MODE"] = mode
def shellcrash_policy() -> dict[str, Any]:
return {
"manual_only": _env_flag("SHELLCRASH_MANUAL_ONLY", True),
"autostart_allowed": _env_flag("SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL", True),
"autostart_on_direct_fail": _env_flag("SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL", True),
"configured_autostart": _env_flag("SHELLCRASH_AUTOSTART", False),
"auto_start_on_web_panel": _env_flag("SHELLCRASH_AUTO_START_ON_WEB_PANEL", False),
"attach_when_direct_ok": _env_flag("SHELLCRASH_ATTACH_WHEN_DIRECT_OK", False),
"attach_neko": os.environ.get("SHELLCRASH_ATTACH_NEKO", "auto"),
"attach_ffmpeg": os.environ.get("SHELLCRASH_ATTACH_FFMPEG", "auto"),
}
def system_network_probe(*, include_proxy: bool = True) -> dict[str, Any]:
direct = _probe_targets(None)
shell = shellcrash_runtime()
shell_cfg = shellcrash_config_status()
proxy = f"http://127.0.0.1:{shell.get('mixed_port') or '7890'}"
proxied = _probe_targets(proxy) if include_proxy and shell.get("running") else []
global_direct_ok = _global_ok(direct)
douyin_direct_ok = _douyin_ok(direct)
global_proxy_ok = _global_ok(proxied)
policy = shellcrash_policy()
recommendation = "direct"
if global_direct_ok:
recommendation = "keep_shellcrash_stopped"
elif shell_cfg.get("available"):
recommendation = "autostart_shellcrash_from_config"
elif shell.get("running") and global_proxy_ok:
recommendation = "shellcrash_running_available"
else:
recommendation = "stage_shellcrash_config_before_youtube"
policy["recommendation"] = recommendation
return {
"ok": bool(global_direct_ok or global_proxy_ok),
"mode": "direct" if global_direct_ok else ("shellcrash" if global_proxy_ok else "failed"),
"direct_ready": bool(global_direct_ok),
"global_direct_ok": bool(global_direct_ok),
"douyin_direct_ok": bool(douyin_direct_ok),
"direct": direct,
"proxied": proxied,
"shellcrash": shell,
"shellcrash_config": shell_cfg,
"shellcrash_autostart_candidate": bool((not global_direct_ok) and shell_cfg.get("available")),
"shellcrash_policy": policy,
"platform": {"system": platform.system(), "machine": platform.machine()},
"summary": (
"Google/YouTube direct egress is available; ShellCrash should stay stopped by default"
if global_direct_ok
else (
"Direct Google/YouTube egress failed; ShellCrash config is available for conditional autostart"
if shell_cfg.get("available")
else "Direct Google/YouTube egress failed; no ShellCrash config is staged"
)
),
}
def youtube_network_preflight() -> dict[str, Any]:
if os.environ.get("YOUTUBE_NETWORK_PREFLIGHT", "1").strip().lower() in {"0", "false", "no", "off"}:
return {"ok": True, "mode": "disabled", "message": "YouTube network preflight disabled"}
direct = _probe_pair(None)
if any(item.get("ok") for item in direct):
direct = _probe_targets(None)
policy = shellcrash_policy()
if _global_ok(direct):
clear_process_proxy_env(mode="direct")
return {
"ok": True,
"mode": "direct",
"message": "YouTube network preflight passed by direct egress",
"message": "YouTube network preflight passed by direct Google/YouTube egress; ShellCrash not attached",
"direct": direct,
"shellcrash": shellcrash_runtime(),
"shellcrash_policy": policy,
"douyin_direct_ok": _douyin_ok(direct),
"platform": {"system": platform.system(), "machine": platform.machine()},
}
shell = shellcrash_runtime()
autostart = {}
if not shell.get("running"):
autostart = autostart_shellcrash_if_configured()
if autostart.get("attempted"):
shell = shellcrash_runtime()
proxy = f"http://127.0.0.1:{shell.get('mixed_port') or '7890'}"
proxied = _probe_pair(proxy) if shell.get("running") else []
if any(item.get("ok") for item in proxied):
proxied = _probe_targets(proxy) if shell.get("running") else []
if _global_ok(proxied):
env = _proxy_env(proxy)
apply_process_proxy_env(env)
return {
"ok": True,
"mode": "shellcrash",
"message": f"YouTube network preflight passed through ShellCrash {proxy}",
"message": f"YouTube network preflight passed through manually running ShellCrash {proxy}",
"direct": direct,
"proxied": proxied,
"shellcrash": shell,
"shellcrash_autostart": autostart,
"shellcrash_policy": policy,
"proxy_env": env,
"douyin_direct_ok": _douyin_ok(direct),
"platform": {"system": platform.system(), "machine": platform.machine()},
}
reason = "direct egress failed"
clear_process_proxy_env(mode="failed")
reason = "direct Google/YouTube egress failed"
if not shell.get("running"):
reason += "; ShellCrash is not running"
else:
@ -168,6 +362,9 @@ def youtube_network_preflight() -> dict[str, Any]:
"direct": direct,
"proxied": proxied,
"shellcrash": shell,
"shellcrash_autostart": autostart,
"shellcrash_policy": policy,
"douyin_direct_ok": _douyin_ok(direct),
"platform": {"system": platform.system(), "machine": platform.machine()},
}

326
d2ypp2/src/ops_center.py Normal file
View File

@ -0,0 +1,326 @@
from __future__ import annotations
import json
import os
import time
import zipfile
from pathlib import Path
from typing import Any
from src.studio_control import list_serial_ports, list_wol_devices, probe_wol_devices
BASE_DIR = Path(__file__).resolve().parent.parent
SNAPSHOT_DIRNAME = "system_snapshots"
def _snapshot_dir(base_dir: Path | None = None) -> Path:
root = base_dir or BASE_DIR
return root / ".process_runner" / SNAPSHOT_DIRNAME
def list_video_devices() -> list[dict[str, Any]]:
devices: list[dict[str, Any]] = []
for path in sorted(Path("/dev").glob("video*")):
if not path.exists():
continue
name = ""
try:
name = (Path("/sys/class/video4linux") / path.name / "name").read_text(encoding="utf-8", errors="ignore").strip()
except OSError:
pass
devices.append({"path": str(path), "name": name, "label": f"{path.name} {name}".strip()})
return devices
def device_inventory(base_dir: Path | None = None, *, refresh: bool = False) -> dict[str, Any]:
wol_payload = probe_wol_devices(base_dir) if refresh else {"devices": list_wol_devices(base_dir)}
wol_devices = wol_payload.get("devices", [])
serial_ports = list_serial_ports()
video_devices = list_video_devices()
return {
"counts": {
"wol": len(wol_devices),
"serial": len(serial_ports),
"video": len(video_devices),
},
"wol": wol_devices,
"serial": serial_ports,
"video": video_devices,
"refreshed": bool(refresh),
"updated_at": time.time(),
}
def automation_recipes() -> list[dict[str, Any]]:
return [
{
"id": "frigate-usb-ntfy",
"title": "USB/UVC camera detected -> Frigate auto-start + ntfy",
"category": "studio",
"priority": "P0",
"trigger": "USB video device appears",
"actions": ["render Frigate camera config", "start Frigate", "send ntfy alert"],
"status": "ready",
},
{
"id": "neko-remote-webrtc-doctor",
"title": "Neko remote mode -> WebRTC/TURN diagnostics",
"category": "remote",
"priority": "P0",
"trigger": "LAN/Remote switch changes to remote",
"actions": ["verify WireGuard", "verify UDP/ICE candidates", "recommend coturn if relay missing"],
"status": "planned",
},
{
"id": "youtube-black-screen-recover",
"title": "YouTube/Neko black screen -> layered recovery",
"category": "live",
"priority": "P0",
"trigger": "Neko session opens but video remains black",
"actions": ["check WebRTC", "check container health", "check Chrome GPU flags", "restart only affected Neko instance"],
"status": "planned",
},
{
"id": "wol-device-online-alert",
"title": "WOL target reachable -> ntfy confirmation",
"category": "studio",
"priority": "P1",
"trigger": "WOL packet sent and ping becomes reachable",
"actions": ["refresh device inventory", "send ntfy alert", "record last_seen"],
"status": "ready",
},
{
"id": "serial-at-session-log",
"title": "AT command session -> command log + reusable presets",
"category": "studio",
"priority": "P1",
"trigger": "serial command sent",
"actions": ["append session log", "detect common modem responses", "offer preset commands"],
"status": "planned",
},
{
"id": "content-rss-live-brief",
"title": "RSS item -> Markdown brief -> live script",
"category": "content",
"priority": "P2",
"trigger": "new RSS/news item selected",
"actions": ["create Markdown note", "draft title/tags", "attach to live task"],
"status": "planned",
},
]
def app_blueprints(installed_ids: set[str] | None = None) -> list[dict[str, Any]]:
installed = installed_ids or set()
rows = [
("homeassistant", "Home Assistant", "studio", "Smart-home automation workspace", "P0"),
("frigate", "Frigate NVR", "studio", "Camera NVR and object detection", "P0"),
("ntfy", "ntfy", "studio", "LAN notification topic server", "P0"),
("coturn", "coturn", "network", "TURN relay for Neko/Frigate WebRTC remote access", "P0"),
("freshrss", "FreshRSS", "content", "RSS intake for content factory", "P1"),
("nextcloud", "Nextcloud", "storage", "Personal NAS and content asset library", "P1"),
("node-red", "Node-RED", "automation", "Low-code automation recipes", "P1"),
("zigbee2mqtt", "Zigbee2MQTT", "iot", "Zigbee device bridge for Home Assistant", "P2"),
("vaultwarden", "Vaultwarden", "security", "Local credential vault", "P2"),
("openwebui", "Open WebUI", "ai", "Local AI workspace for scripts and ops", "P2"),
]
return [
{
"id": service_id,
"title": title,
"category": category,
"description": description,
"priority": priority,
"installed": service_id in installed,
"status": "installed" if service_id in installed else "blueprint",
}
for service_id, title, category, description, priority in rows
]
def system_doctor(services: list[dict[str, Any]], deployment: dict[str, Any] | None = None) -> dict[str, Any]:
service_by_id = {str(item.get("service_id")): item for item in services}
checks: list[dict[str, Any]] = []
def add(check_id: str, label: str, ok: bool, severity: str, detail: str, recommendation: str = "") -> None:
checks.append(
{
"id": check_id,
"label": label,
"ok": bool(ok),
"severity": "info" if ok else severity,
"detail": detail,
"recommendation": recommendation,
}
)
if deployment:
add(
"deployment",
"Deployment acceptance",
bool(deployment.get("ready", False)),
"critical",
f"{deployment.get('pass_count', 0)}/{deployment.get('total_count', 0)} checks passed",
"Open /deploy/check and repair failing edge/mDNS/API checks.",
)
for service_id, label, severity in [
("shellcrash", "ShellCrash network engine", "warning"),
("srs", "SRS stream relay", "critical"),
("neko", "Neko browser pool", "critical"),
("homeassistant", "Home Assistant", "warning"),
("ntfy", "ntfy alerts", "warning"),
("wol", "Wake-on-LAN", "warning"),
]:
svc = service_by_id.get(service_id, {})
available = bool(svc.get("available"))
running = bool(svc.get("running"))
expected_running = service_id not in {"wol"}
ok = available and (running or not expected_running)
add(
f"service:{service_id}",
label,
ok,
severity,
str(svc.get("detail") or svc.get("status") or "missing"),
f"Run service action start/restart for {service_id}." if available and expected_running else f"Enable {service_id} in system-stack.env.",
)
enabled = [item for item in services if item.get("available")]
running = [item for item in enabled if item.get("running")]
critical_failures = [item for item in checks if not item["ok"] and item["severity"] == "critical"]
warnings = [item for item in checks if not item["ok"] and item["severity"] == "warning"]
score = max(0, min(100, 100 - len(critical_failures) * 22 - len(warnings) * 8))
status = "excellent" if score >= 90 else "good" if score >= 75 else "degraded" if score >= 50 else "critical"
recommendations = [item["recommendation"] for item in checks if not item["ok"] and item.get("recommendation")]
return {
"score": score,
"status": status,
"services_running": len(running),
"services_available": len(enabled),
"critical": len(critical_failures),
"warnings": len(warnings),
"checks": checks,
"recommendations": recommendations[:8],
}
def _snapshot_candidates(base_dir: Path) -> list[Path]:
patterns = [
"config/*.ini",
"config/*.env",
"config/*.example",
"config/*.json",
"config/*.yaml",
"config/*.yml",
"live-platform/config/defaults/**/*.json",
"services/*/docker-compose.yml",
"services/*/docker-compose.yaml",
"services/*/config/**/*",
"services/*/conf/**/*",
"services/neko/*.conf",
"services/neko/policies/**/*",
"services/neko/provisioning/**/*",
]
out: list[Path] = []
seen: set[Path] = set()
for pattern in patterns:
for path in base_dir.glob(pattern):
if not path.is_file():
continue
try:
resolved = path.resolve()
except OSError:
continue
if resolved in seen:
continue
seen.add(resolved)
out.append(path)
return sorted(out)
def list_system_snapshots(base_dir: Path | None = None, limit: int = 20) -> list[dict[str, Any]]:
directory = _snapshot_dir(base_dir)
if not directory.is_dir():
return []
rows: list[dict[str, Any]] = []
for path in sorted(directory.glob("*.zip"), key=lambda item: item.stat().st_mtime, reverse=True)[:limit]:
stat = path.stat()
rows.append(
{
"id": path.name,
"name": path.name,
"path": str(path),
"size": stat.st_size,
"created_at": stat.st_mtime,
}
)
return rows
def create_system_snapshot(base_dir: Path | None = None, *, reason: str = "manual") -> dict[str, Any]:
root = base_dir or BASE_DIR
directory = _snapshot_dir(root)
directory.mkdir(parents=True, exist_ok=True)
safe_reason = "".join(ch if ch.isalnum() or ch in {"-", "_"} else "_" for ch in (reason or "manual"))[:48] or "manual"
name = f"{time.strftime('%Y%m%d_%H%M%S')}__{safe_reason}.zip"
target = directory / name
files = _snapshot_candidates(root)
included = 0
skipped = 0
with zipfile.ZipFile(target, "w", compression=zipfile.ZIP_DEFLATED) as archive:
manifest = {
"created_at": time.time(),
"reason": safe_reason,
"root": str(root),
"file_count": 0,
}
for path in files:
try:
stat = path.stat()
except OSError:
skipped += 1
continue
if stat.st_size > 2 * 1024 * 1024:
skipped += 1
continue
archive.write(path, path.relative_to(root).as_posix())
included += 1
manifest["file_count"] = included
manifest["skipped"] = skipped
archive.writestr("manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2))
try:
target.chmod(0o666)
except OSError:
pass
stat = target.stat()
return {
"message": "System snapshot created",
"snapshot": {
"id": name,
"name": name,
"path": str(target),
"size": stat.st_size,
"created_at": stat.st_mtime,
"included": included,
"skipped": skipped,
},
"snapshots": list_system_snapshots(root),
}
def studio_ops_summary(
services: list[dict[str, Any]],
deployment: dict[str, Any] | None,
base_dir: Path | None = None,
*,
refresh: bool = False,
) -> dict[str, Any]:
installed = {str(item.get("service_id")) for item in services}
return {
"doctor": system_doctor(services, deployment),
"inventory": device_inventory(base_dir, refresh=refresh),
"recipes": automation_recipes(),
"apps": app_blueprints(installed),
"backups": {"snapshots": list_system_snapshots(base_dir)},
}

View File

@ -32,6 +32,38 @@ def _has_any(text: str, patterns: tuple[str, ...]) -> bool:
return any(p in text for p in patterns)
def _looks_like_youtube_key_rejected(tail: str) -> bool:
youtube_output = _has_any(
tail,
(
"rtmps://a.rtmps.youtube.com/live2/",
"rtmp://a.rtmp.youtube.com/live2/",
"youtube.com/live2/",
),
)
if not youtube_output:
return False
if not _has_any(tail, ("error opening output", "error opening output file", "error opening output files")):
return False
return _has_any(
tail,
(
"io error: end of file",
"input/output error",
"error in the pull function",
"tls @",
"401",
"403",
"unauthorized",
"forbidden",
),
)
def _looks_like_ffmpeg_progress(tail: str) -> bool:
return "frame=" in tail and "time=" in tail and _has_any(tail, ("bitrate=", "speed="))
def coerce_declared_process_status(backend_mode: str, process_status: str, declared: bool) -> str:
status = (process_status or "").strip().lower()
mode = (backend_mode or "").strip().lower()
@ -56,20 +88,29 @@ def summarize_process_activity(
business_status = "inactive"
business_note = "Process is not running"
has_recent_ffmpeg_progress = _looks_like_ffmpeg_progress(tail) and (
log_age_seconds is None or log_age_seconds <= 20
)
if status in {"online", "running"}:
if family == "youtube" and not pids and not has_recent_ffmpeg_progress and _looks_like_youtube_key_rejected(tail):
business_status = "youtube_key_rejected"
business_note = (
"YouTube rejected the RTMPS output. The stream key is likely invalid, expired, "
"or not for this live event; if the key is correct, check network/proxy access to YouTube RTMPS."
)
elif status in {"online", "running"}:
if _has_any(tail, ("请在 ", "配置 key", "stream_key", "key=你的stream_key")):
business_status = "misconfigured"
business_note = "YouTube stream key is missing or invalid"
elif pids:
elif pids or has_recent_ffmpeg_progress:
business_status = "streaming"
business_note = "FFmpeg relay worker is running"
business_note = "FFmpeg relay worker is running" if pids else "FFmpeg relay is emitting video frames"
elif log_age_seconds is not None and log_age_seconds > 180:
business_status = "stale"
business_note = "Process is online but the log heartbeat is stale"
elif family == "youtube" and _has_any(
tail,
("等待直播", "循环等待", "检测直播间中", "没有正在监测的直播"),
("等待直播", "循环等待", "检测直播间中", "没有正在监测的直播", "无录制任务", "网址内容获取失败"),
):
business_status = "waiting_source"
business_note = "Waiting for the upstream live source"

View File

@ -21,6 +21,8 @@ RUNTIME_DIRS = (
".process_runner",
"services/neko",
"services/neko/data",
"services/homeassistant",
"services/frigate",
)
@ -60,6 +62,10 @@ def ensure_runtime_layout(base_dir: str | Path) -> list[str]:
except OSError as exc:
issues.append(f"{path}: mkdir failed: {exc}")
continue
try:
path.chmod(0o777)
except OSError:
pass
if not os.access(path, os.W_OK | os.X_OK):
issues.append(f"{path}: directory is not writable by uid={_effective_uid()}")
return issues

View File

@ -0,0 +1,356 @@
from __future__ import annotations
import ipaddress
import json
import os
import re
import select
import socket
import subprocess
import time
from pathlib import Path
from typing import Any
try:
import termios
except ModuleNotFoundError: # pragma: no cover - Windows import fallback
termios = None # type: ignore[assignment]
_MAC_HEX_RE = re.compile(r"^[0-9A-Fa-f]{12}$")
_SERIAL_PORT_RE = re.compile(r"^(?:/dev/tty(?:USB|ACM|AMA|S|THS|XRUSB)[A-Za-z0-9._/-]*|COM\d+)$", re.IGNORECASE)
_WOL_IGNORED_IFACE_PREFIXES = ("docker", "br-", "veth", "virbr", "lxc", "wg", "tailscale")
BASE_DIR = Path(__file__).resolve().parent.parent
WOL_DEVICES_FILE = BASE_DIR / "config" / "wol_devices.json"
def normalize_mac_address(value: str) -> str:
cleaned = re.sub(r"[^0-9A-Fa-f]", "", (value or "").strip())
if not _MAC_HEX_RE.fullmatch(cleaned):
raise ValueError("Invalid MAC address")
return ":".join(cleaned.upper()[i : i + 2] for i in range(0, 12, 2))
def _magic_packet(mac: str) -> bytes:
compact = mac.replace(":", "")
return bytes.fromhex("FF" * 6 + compact * 16)
def send_wake_on_lan(mac: str, broadcast: str = "255.255.255.255", port: int = 9) -> dict[str, Any]:
normalized = normalize_mac_address(mac)
target = (broadcast or "255.255.255.255").strip()
try:
ipaddress.IPv4Address(target)
except ValueError as exc:
raise ValueError("Broadcast must be an IPv4 address") from exc
try:
resolved_port = int(port)
except (TypeError, ValueError) as exc:
raise ValueError("Port must be between 1 and 65535") from exc
if not 1 <= resolved_port <= 65535:
raise ValueError("Port must be between 1 and 65535")
packet = _magic_packet(normalized)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sent = sock.sendto(packet, (target, resolved_port))
finally:
sock.close()
return {
"message": f"Wake-on-LAN packet sent to {normalized} via {target}:{resolved_port}",
"mac": normalized,
"broadcast": target,
"port": resolved_port,
"bytes": sent,
}
def _wol_store_path(base_dir: Path | None = None) -> Path:
root = base_dir or BASE_DIR
return root / "config" / "wol_devices.json"
def _load_wol_devices(base_dir: Path | None = None) -> list[dict[str, Any]]:
path = _wol_store_path(base_dir)
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return []
if not isinstance(data, list):
return []
out: list[dict[str, Any]] = []
for item in data:
if not isinstance(item, dict):
continue
mac = str(item.get("mac") or "").strip()
try:
norm = normalize_mac_address(mac)
except ValueError:
continue
out.append(
{
"id": norm,
"name": str(item.get("name") or item.get("ip") or norm).strip(),
"mac": norm,
"ip": str(item.get("ip") or "").strip(),
"reachable": bool(item.get("reachable")),
"source": str(item.get("source") or "manual"),
"last_seen": float(item.get("last_seen") or 0),
"updated_at": float(item.get("updated_at") or 0),
}
)
return sorted(out, key=lambda item: (not item.get("reachable"), item.get("name") or item["mac"]))
def _save_wol_devices(devices: list[dict[str, Any]], base_dir: Path | None = None) -> None:
path = _wol_store_path(base_dir)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(devices, ensure_ascii=False, indent=2), encoding="utf-8")
try:
path.chmod(0o666)
except OSError:
pass
def _run_text(args: list[str], timeout: float = 3.0) -> str:
try:
completed = subprocess.run(args, text=True, capture_output=True, timeout=timeout, check=False)
except (OSError, subprocess.SubprocessError):
return ""
return completed.stdout or ""
def _wol_probe_networks() -> list[ipaddress.IPv4Network]:
raw = (os.environ.get("WOL_PROBE_CIDR") or "").strip()
networks: list[ipaddress.IPv4Network] = []
for item in re.split(r"[,;\s]+", raw):
if not item:
continue
try:
network = ipaddress.ip_network(item, strict=False)
except ValueError:
continue
if isinstance(network, ipaddress.IPv4Network):
networks.append(network)
return networks
def _wol_ip_allowed(ip: ipaddress.IPv4Address, networks: list[ipaddress.IPv4Network]) -> bool:
if ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_unspecified:
return False
if networks:
return any(ip in network for network in networks)
return True
def _wol_iface_allowed(iface: str) -> bool:
name = (iface or "").strip().lower()
if not name:
return True
return not name.startswith(_WOL_IGNORED_IFACE_PREFIXES)
def _ip_neigh_devices() -> list[dict[str, Any]]:
raw = _run_text(["ip", "neigh", "show"], timeout=2.5)
devices: list[dict[str, Any]] = []
networks = _wol_probe_networks()
for line in raw.splitlines():
parts = line.split()
if len(parts) < 5 or "lladdr" not in parts:
continue
ip = parts[0]
iface = parts[parts.index("dev") + 1] if "dev" in parts and parts.index("dev") + 1 < len(parts) else ""
if not _wol_iface_allowed(iface):
continue
try:
ip_obj = ipaddress.IPv4Address(ip)
except ValueError:
continue
if not _wol_ip_allowed(ip_obj, networks):
continue
mac = parts[parts.index("lladdr") + 1]
try:
norm = normalize_mac_address(mac)
except ValueError:
continue
state = parts[-1].lower()
if state in {"failed", "incomplete"}:
continue
devices.append(
{
"id": norm,
"name": ip,
"ip": ip,
"mac": norm,
"reachable": state in {"reachable", "stale", "delay", "probe", "permanent"},
"source": "neigh",
"last_seen": time.time(),
"updated_at": time.time(),
}
)
return devices
def _ping_host(ip: str, timeout: float = 1.0) -> bool:
try:
ipaddress.IPv4Address(ip)
except ValueError:
return False
try:
completed = subprocess.run(
["ping", "-c", "1", "-W", str(max(1, int(timeout))), ip],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
except OSError:
return False
return completed.returncode == 0
def list_wol_devices(base_dir: Path | None = None) -> list[dict[str, Any]]:
return _load_wol_devices(base_dir)
def probe_wol_devices(base_dir: Path | None = None) -> dict[str, Any]:
now = time.time()
existing = {item["mac"]: item for item in _load_wol_devices(base_dir)}
seen: set[str] = set()
for item in list(existing.values()):
ip = str(item.get("ip") or "").strip()
if ip:
reachable = _ping_host(ip)
item["reachable"] = reachable
item["updated_at"] = now
if reachable:
item["last_seen"] = now
for item in _ip_neigh_devices():
seen.add(item["mac"])
current = existing.get(item["mac"], {})
merged = {**item, **{k: v for k, v in current.items() if k in {"name", "source"} and v}}
if current.get("name") and current.get("name") != current.get("ip"):
merged["name"] = current["name"]
if current.get("source") == "manual":
merged["source"] = "manual"
existing[item["mac"]] = merged
devices = [
item
for item in existing.values()
if item.get("source") == "manual" or item["mac"] in seen
]
devices = sorted(devices, key=lambda item: (not item.get("reachable"), item.get("name") or item["mac"]))
_save_wol_devices(devices, base_dir)
return {"devices": devices, "count": len(devices), "probed_at": now}
def upsert_wol_device(name: str, mac: str, ip: str = "", base_dir: Path | None = None) -> dict[str, Any]:
norm = normalize_mac_address(mac)
ip_value = (ip or "").strip()
if ip_value:
try:
ipaddress.IPv4Address(ip_value)
except ValueError as exc:
raise ValueError("Device IP must be an IPv4 address") from exc
devices = {item["mac"]: item for item in _load_wol_devices(base_dir)}
now = time.time()
current = devices.get(norm, {})
devices[norm] = {
"id": norm,
"name": (name or ip_value or norm).strip(),
"mac": norm,
"ip": ip_value,
"reachable": bool(current.get("reachable")),
"source": "manual",
"last_seen": float(current.get("last_seen") or 0),
"updated_at": now,
}
out = sorted(devices.values(), key=lambda item: (not item.get("reachable"), item.get("name") or item["mac"]))
_save_wol_devices(out, base_dir)
return devices[norm]
def delete_wol_device(mac: str, base_dir: Path | None = None) -> dict[str, Any]:
norm = normalize_mac_address(mac)
devices = [item for item in _load_wol_devices(base_dir) if item["mac"] != norm]
_save_wol_devices(devices, base_dir)
return {"message": "Device removed", "mac": norm, "devices": devices}
def list_serial_ports() -> list[dict[str, Any]]:
patterns = ["/dev/ttyUSB*", "/dev/ttyACM*", "/dev/ttyAMA*", "/dev/ttyTHS*", "/dev/ttyXRUSB*", "/dev/ttyS*"]
ports: list[dict[str, Any]] = []
seen: set[str] = set()
for pattern in patterns:
for path in sorted(Path("/").glob(pattern.lstrip("/"))):
raw = "/" + path.as_posix().lstrip("/")
if raw in seen:
continue
seen.add(raw)
name = ""
try:
name = (Path("/sys/class/tty") / Path(raw).name / "device" / "product").read_text(encoding="utf-8", errors="ignore").strip()
except OSError:
pass
ports.append({"path": raw, "label": f"{Path(raw).name} {name}".strip(), "name": name})
return ports
def _baud_constant(baudrate: int) -> int:
if termios is None:
raise RuntimeError("Serial control requires Linux termios support")
mapping = {
9600: termios.B9600,
19200: termios.B19200,
38400: termios.B38400,
57600: termios.B57600,
115200: termios.B115200,
}
if hasattr(termios, "B230400"):
mapping[230400] = termios.B230400
return mapping.get(int(baudrate), termios.B115200)
def send_serial_command(port: str, command: str, baudrate: int = 115200, timeout: float = 2.0, append_crlf: bool = True) -> dict[str, Any]:
if termios is None:
raise RuntimeError("Serial control requires Linux termios support")
target = (port or "").strip()
if not _SERIAL_PORT_RE.fullmatch(target):
raise ValueError("Unsupported serial port path")
if not command:
raise ValueError("Serial command is empty")
baud = _baud_constant(int(baudrate))
fd = os.open(target, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
old_attrs = termios.tcgetattr(fd)
try:
attrs = termios.tcgetattr(fd)
attrs[0] = 0
attrs[1] = 0
attrs[2] = termios.CLOCAL | termios.CREAD | termios.CS8
attrs[3] = 0
attrs[4] = baud
attrs[5] = baud
termios.tcsetattr(fd, termios.TCSANOW, attrs)
payload = command.encode("utf-8", "replace")
if append_crlf:
payload += b"\r\n"
os.write(fd, payload)
chunks: list[bytes] = []
deadline = time.time() + max(0.2, min(float(timeout), 10.0))
while time.time() < deadline:
remaining = max(0.05, deadline - time.time())
readable, _, _ = select.select([fd], [], [], remaining)
if not readable:
continue
try:
chunk = os.read(fd, 4096)
except BlockingIOError:
continue
if not chunk:
break
chunks.append(chunk)
text = b"".join(chunks).decode("utf-8", "replace")
return {"port": target, "baudrate": int(baudrate), "command": command, "response": text, "bytes": len(payload)}
finally:
termios.tcsetattr(fd, termios.TCSANOW, old_attrs)
os.close(fd)

View File

@ -18,6 +18,12 @@ from typing import Any, Iterable, Optional
BACKEND_STATE_VERSION = 1
if not hasattr(os, "getpgid"):
def _unsupported_getpgid(pid: int) -> int:
raise OSError("process groups are not supported on this platform")
os.getpgid = _unsupported_getpgid # type: ignore[attr-defined]
def strip_ansi_codes(text: str) -> str:
return re.sub(r"\x1b\[[0-9;]*m", "", text)
@ -437,13 +443,13 @@ def resolve_pm2_bin() -> Optional[str]:
def preferred_python_interpreter(base_dir: Path) -> str:
venv_python = base_dir / ".venv" / "bin" / "python"
candidates = [
str(venv_python),
shutil_which("python3"),
shutil_which("python"),
sys.executable,
]
for candidate in candidates:
if venv_python.is_file() and os.access(str(venv_python), os.X_OK):
return str(venv_python)
for candidate in (shutil_which("python3"), shutil_which("python")):
if not candidate:
continue
return str(candidate)
for candidate in (sys.executable,):
if not candidate:
continue
path = Path(candidate).expanduser()

View File

@ -412,8 +412,8 @@ def save_imported_wireguard_config(
"relative_path": str(target.relative_to(repo_root)),
"summary_path": str(summary_path),
"linux_apply_commands": [
f"sudo install -m 600 {target} /etc/wireguard/{safe_name}.conf",
f"sudo systemctl enable --now wg-quick@{safe_name}",
f"install -m 600 {target} /etc/wireguard/{safe_name}.conf",
f"systemctl enable --now wg-quick@{safe_name}",
],
}
)
@ -856,6 +856,30 @@ def _read_stack_env(repo_root: Path) -> dict[str, str]:
return out
def _upsert_stack_env_values(repo_root: Path, values: dict[str, str]) -> bool:
env_path = repo_root / "config" / "system-stack.env"
env_path.parent.mkdir(parents=True, exist_ok=True)
lines = env_path.read_text(encoding="utf-8", errors="replace").splitlines() if env_path.is_file() else []
changed = False
for key, value in values.items():
prefix = f"{key}="
next_line = f"{key}={value}"
for idx, raw in enumerate(lines):
if raw.strip().startswith(prefix):
if raw != next_line:
lines[idx] = next_line
changed = True
break
else:
if lines and lines[-1].strip():
lines.append("")
lines.append(next_line)
changed = True
if changed:
env_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
return changed
def _env_int(env: dict[str, str], key: str, default: int) -> int:
raw = str(env.get(key, "")).strip()
if not raw:
@ -880,12 +904,102 @@ def _split_host_list(*values: str | None) -> list[str]:
return hosts
def _host_is_private_ipv4(host: str) -> bool:
def _normalize_neko_access_mode(value: str | None) -> str:
raw = str(value or "lan").strip().lower()
if raw in {"remote", "wg", "wireguard", "wan"}:
return "remote"
return "lan"
def _interface_name_is_physical_lan(name: str) -> bool:
low = name.strip().lower()
if not low:
return False
prefixes = ("lo", "docker", "br-", "veth", "virbr", "tun", "tap", "zt", "tailscale", "wg", "wireguard", "sit", "dummy")
return not low.startswith(prefixes) and not low.startswith("p2p-dev-") and not low.startswith("mon.")
def _extract_route_token(text: str, token: str) -> str:
parts = text.split()
for idx, part in enumerate(parts):
if part == token and idx + 1 < len(parts):
return parts[idx + 1]
return ""
def _addr_for_iface(name: str) -> str:
if not name:
return ""
result = _run_command(["ip", "-4", "addr", "show", "dev", name], timeout=2.0)
if not result["ok"]:
return ""
for raw in result["stdout"].splitlines():
parts = raw.strip().split()
if len(parts) >= 2 and parts[0] == "inet":
return parts[1].split("/", 1)[0]
return ""
def _detect_preferred_lan_ip() -> str:
route = _run_command(["ip", "-4", "route", "get", "1.1.1.1"], timeout=2.0)
if route["ok"] and route["stdout"]:
iface = _extract_route_token(route["stdout"], "dev")
src = _extract_route_token(route["stdout"], "src")
if src and _interface_name_is_physical_lan(iface):
return src
default_route = _run_command(["ip", "route", "show", "default"], timeout=2.0)
if default_route["ok"] and default_route["stdout"]:
iface = _extract_route_token(default_route["stdout"].splitlines()[0], "dev")
if _interface_name_is_physical_lan(iface):
addr = _addr_for_iface(iface)
if addr:
return addr
hostname = _run_command(["hostname", "-I"], timeout=2.0)
if hostname["ok"]:
for raw in hostname["stdout"].split():
if raw.startswith(("127.", "169.254.")):
continue
try:
ip = ipaddress.ip_address(raw)
except ValueError:
continue
if isinstance(ip, ipaddress.IPv4Address):
return str(ip)
return ""
def _ip_from_interface(value: str) -> str:
try:
return str(ipaddress.ip_interface(str(value)).ip)
except ValueError:
return ""
def _wireguard_candidate_hosts(interfaces: list[dict[str, Any]]) -> list[str]:
hosts: list[str] = []
for item in interfaces:
for raw in item.get("addresses") or []:
host = _ip_from_interface(str(raw))
if not host:
continue
try:
ip = ipaddress.ip_address(host)
except ValueError:
return False
return isinstance(ip, ipaddress.IPv4Address) and ip.is_private
continue
if isinstance(ip, ipaddress.IPv4Address) and not ip.is_loopback and host not in hosts:
hosts.append(host)
return hosts
def _configured_neko_wireguard_hosts(env: dict[str, str]) -> list[str]:
return _split_host_list(
env.get("NEKO_WIREGUARD_HOSTS"),
env.get("NEKO_WIREGUARD_HOST"),
env.get("NEKO_WG_HOST"),
env.get("WIREGUARD_HOST"),
)
def _neko_http_ports(env: dict[str, str]) -> list[int]:
@ -895,29 +1009,70 @@ def _neko_http_ports(env: dict[str, str]) -> list[int]:
return [_env_int(env, f"NEKO_HTTP_PORT_{idx}", base + idx - 1) for idx in range(1, count + 1)]
def _neko_wireguard_hosts(env: dict[str, str]) -> list[str]:
hosts = _split_host_list(
env.get("NEKO_WIREGUARD_HOSTS"),
env.get("NEKO_WIREGUARD_HOST"),
env.get("NEKO_WG_HOST"),
env.get("WIREGUARD_HOST"),
)
nat1to1 = str(env.get("NEKO_WEBRTC_NAT1TO1") or "").strip()
if nat1to1 and _host_is_private_ipv4(nat1to1) and nat1to1 not in hosts:
hosts.append(nat1to1)
return hosts
def _neko_remote_urls(env: dict[str, str]) -> list[dict[str, Any]]:
def _neko_access_urls(env: dict[str, str], *, mode: str, target_host: str) -> list[dict[str, Any]]:
urls: list[dict[str, Any]] = []
ports = _neko_http_ports(env)
for host in _neko_wireguard_hosts(env):
for idx, port in enumerate(ports, start=1):
urls.append({"id": idx, "kind": "wireguard", "host": host, "port": port, "url": f"http://{host}:{port}"})
for host in _split_host_list(env.get("NEKO_PUBLIC_HOSTS"), env.get("NEKO_PUBLIC_HOST")):
for idx, port in enumerate(ports, start=1):
urls.append({"id": idx, "kind": "public", "host": host, "port": port, "url": f"http://{host}:{port}"})
if not target_host:
return urls
kind = "wireguard" if mode == "remote" else "lan"
for idx, port in enumerate(_neko_http_ports(env), start=1):
urls.append({"id": idx, "kind": kind, "host": target_host, "port": port, "url": f"http://{target_host}:{port}"})
return urls
def _neko_access_status(
repo_root: Path,
*,
interfaces: list[dict[str, Any]],
active: bool,
) -> dict[str, Any]:
env = _read_stack_env(repo_root)
mode = _normalize_neko_access_mode(env.get("NEKO_ACCESS_MODE"))
configured_hosts = _configured_neko_wireguard_hosts(env)
candidates = _wireguard_candidate_hosts(interfaces)
wireguard_host = next((host for host in configured_hosts if host), "") or next(iter(candidates), "")
lan_host = _detect_preferred_lan_ip()
target = wireguard_host if mode == "remote" else lan_host
nat1to1 = str(env.get("NEKO_WEBRTC_NAT1TO1") or "").strip()
return {
"mode": mode,
"mode_label": "remote" if mode == "remote" else "lan",
"wireguard_active": bool(active),
"remote_ready": bool(active and wireguard_host),
"nat1to1": nat1to1,
"lan_host": lan_host,
"wireguard_host": wireguard_host,
"configured_wireguard_hosts": configured_hosts,
"detected_wireguard_hosts": candidates,
"target_nat1to1": target,
"needs_reconfigure": bool(target and nat1to1 != target),
"remote_urls": _neko_access_urls(env, mode=mode, target_host=target),
}
def _reconfigure_neko_containers(repo_root: Path) -> dict[str, Any]:
service_ctl = repo_root / "scripts" / "linux" / "service_ctl.sh"
if not service_ctl.is_file():
return {"ok": False, "reason": "service_ctl_missing"}
try:
completed = subprocess.run(
["bash", str(service_ctl), "neko", "reconfigure"],
cwd=str(repo_root),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
timeout=180,
check=False,
)
except subprocess.TimeoutExpired:
return {"ok": False, "reason": "reconfigure_timeout"}
except OSError as exc:
return {"ok": False, "reason": f"reconfigure_failed: {exc}"}
output = (completed.stdout or "").strip()
return {
"ok": completed.returncode == 0,
"reason": "" if completed.returncode == 0 else f"reconfigure_exit_{completed.returncode}",
"output": "\n".join(output.splitlines()[-20:]),
}
def _wireguard_quality(
@ -1031,7 +1186,6 @@ def wireguard_runtime_status(*, repo_root: Path) -> dict[str, Any]:
if commands["systemctl"]:
item["systemd"] = _systemd_unit_state(f"wg-quick@{item['name']}.service")
env = _read_stack_env(repo_root)
configured_peer_count = _configured_wireguard_peer_count(interfaces)
if not configured_peer_count and not interfaces:
configured_peer_count = sum(int(cfg.get("peer_count") or 0) for cfg in [*system_configs, *repo_configs])
@ -1058,12 +1212,11 @@ def wireguard_runtime_status(*, repo_root: Path) -> dict[str, Any]:
recommendations.append("Add PersistentKeepalive=25 to VPS Endpoint peers for stable NAT traversal")
if any(route.get("uses_wireguard_interface") for route in endpoint_routes):
recommendations.append("WireGuard Endpoint route points at the WireGuard interface; add a physical gateway bypass route")
if interfaces and not env.get("NEKO_WEBRTC_NAT1TO1"):
recommendations.append("Set NEKO_WEBRTC_NAT1TO1 to the WireGuard client IP for stable external Neko WebRTC")
if quality["status"] in {"idle", "stale"}:
recommendations.append("Peer handshake is stale; check VPS UDP 51820 firewall, endpoint bypass route, and PersistentKeepalive=25")
if interfaces and not _neko_wireguard_hosts(env):
recommendations.append("Set NEKO_WIREGUARD_HOST to the board WireGuard IP so the panel can show direct Neko links")
neko_access = _neko_access_status(repo_root, interfaces=interfaces, active=bool(interfaces))
if neko_access["mode"] == "remote" and not neko_access["remote_ready"]:
recommendations.append("Neko remote mode is selected, but no active WireGuard address is available")
return {
"platform": {
@ -1080,20 +1233,56 @@ def wireguard_runtime_status(*, repo_root: Path) -> dict[str, Any]:
"system_configs": system_configs,
"repo_configs": repo_configs,
"shellcrash": _shellcrash_status(),
"neko": {
"nat1to1": env.get("NEKO_WEBRTC_NAT1TO1") or "",
"wireguard_hosts": env.get("NEKO_WIREGUARD_HOSTS") or env.get("NEKO_WIREGUARD_HOST") or "",
"remote_urls": _neko_remote_urls(env),
"browser_proxy": env.get("NEKO_BROWSER_PROXY") or "auto",
"browser_proxy_bypass": env.get("NEKO_BROWSER_PROXY_BYPASS") or "auto",
"http_port": env.get("NEKO_HTTP_PORT") or "9200",
"http_port_2": env.get("NEKO_HTTP_PORT_2") or "9201",
},
"neko_access": neko_access,
"recommendations": recommendations,
"last_checked_at": int(time.time()),
}
def configure_neko_wireguard_access(
*,
repo_root: Path,
mode: str,
restart: bool = True,
status: dict[str, Any] | None = None,
) -> dict[str, Any]:
mode = _normalize_neko_access_mode(mode)
if status is None:
status = wireguard_runtime_status(repo_root=repo_root)
interfaces = status.get("interfaces") if isinstance(status.get("interfaces"), list) else []
access = _neko_access_status(repo_root, interfaces=interfaces, active=bool(status.get("active")))
if mode == "remote":
if not access.get("remote_ready"):
raise WireGuardConfigError("WireGuard is not active or no local WireGuard address is available; cannot switch Neko to remote mode")
target = str(access.get("wireguard_host") or "").strip()
else:
target = str(access.get("lan_host") or "").strip()
if not target:
raise WireGuardConfigError("No physical LAN IP was detected; cannot switch Neko to LAN mode")
updates = {
"NEKO_ACCESS_MODE": mode,
"NEKO_WEBRTC_NAT1TO1": target,
}
if mode == "remote" and not _configured_neko_wireguard_hosts(_read_stack_env(repo_root)):
updates["NEKO_WIREGUARD_HOST"] = target
changed = _upsert_stack_env_values(repo_root, updates)
reconfigure: dict[str, Any] = {"ok": True, "skipped": True, "reason": "unchanged"}
if restart and changed:
reconfigure = _reconfigure_neko_containers(repo_root)
next_status = wireguard_runtime_status(repo_root=repo_root)
result = dict(next_status.get("neko_access") or {})
result.update(
{
"changed": changed,
"restart_requested": restart,
"reconfigured": bool(reconfigure.get("ok") and not reconfigure.get("skipped")),
"reconfigure": reconfigure,
}
)
return result
def apply_wireguard_config(
content: str,
*,
@ -1112,15 +1301,12 @@ def apply_wireguard_config(
if not shutil.which("wg-quick"):
raise WireGuardConfigError("wg-quick is not installed")
prefix: list[str] = []
if hasattr(os, "geteuid") and os.geteuid() != 0:
if not shutil.which("sudo"):
raise WireGuardConfigError("root or sudo is required to apply WireGuard config")
prefix = ["sudo", "-n"]
raise WireGuardConfigError("live-console must run as root to apply WireGuard config")
commands = [
[*prefix, "mkdir", "-p", "/etc/wireguard"],
[*prefix, "install", "-m", "600", str(source), str(target)],
["mkdir", "-p", "/etc/wireguard"],
["install", "-m", "600", str(source), str(target)],
]
for cmd in commands:
run = _run_command(cmd, timeout=8.0)
@ -1131,7 +1317,7 @@ def apply_wireguard_config(
active = _run_command(["systemctl", "is-active", unit], timeout=2.0) if shutil.which("systemctl") else {"ok": False}
if shutil.which("systemctl"):
action = "restart" if active.get("ok") else "enable"
cmd = [*prefix, "systemctl", action, unit] if action == "restart" else [*prefix, "systemctl", "enable", "--now", unit]
cmd = ["systemctl", action, unit] if action == "restart" else ["systemctl", "enable", "--now", unit]
run = _run_command(cmd, timeout=20.0)
if not run["ok"]:
raise WireGuardConfigError(run["stderr"] or run["stdout"] or f"command failed: {' '.join(cmd)}")

View File

@ -0,0 +1,829 @@
from __future__ import annotations
import hashlib
import json
import os
import re
import sqlite3
import time
import uuid
from pathlib import Path
from typing import Any
from src.control_plane import CONFIG_DIR
_DB_NAME = "hub_state.sqlite"
_DOUYIN_ROOM_RE = re.compile(r"(?:https?://)?(?:www\.)?live\.douyin\.com/([A-Za-z0-9_-]+)", re.IGNORECASE)
_ROOM_HINT_RE = re.compile(r"(?:room[_\s-]?id|roomId|webcast_id)\D{0,8}([A-Za-z0-9_-]{4,})", re.IGNORECASE)
_URL_RE = re.compile(r"https?://[^\s\"'<>]+", re.IGNORECASE)
_KEY_RE = re.compile(r"^\s*key\s*=\s*(.+?)\s*$", re.IGNORECASE | re.MULTILINE)
def _db_path(db_path: Path | None = None) -> Path:
return db_path or (CONFIG_DIR / _DB_NAME)
def _chmod_runtime_files(path: Path) -> None:
try:
path.parent.mkdir(parents=True, exist_ok=True)
os.chmod(path.parent, 0o775)
except OSError:
pass
for item in (path, path.with_name(f"{path.name}-wal"), path.with_name(f"{path.name}-shm")):
try:
if item.exists():
os.chmod(item, 0o664)
except OSError:
pass
def _connect(db_path: Path | None = None) -> sqlite3.Connection:
path = _db_path(db_path)
_chmod_runtime_files(path)
conn = sqlite3.connect(str(path), timeout=12)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA busy_timeout=12000")
conn.execute(
"""
CREATE TABLE IF NOT EXISTS youtube_live_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_uuid TEXT NOT NULL UNIQUE,
process TEXT NOT NULL DEFAULT '',
mode TEXT NOT NULL DEFAULT '',
channel_id TEXT NOT NULL DEFAULT '',
channel_name TEXT NOT NULL DEFAULT '',
source_platform TEXT NOT NULL DEFAULT 'douyin',
source_url TEXT NOT NULL DEFAULT '',
source_room_id TEXT NOT NULL DEFAULT '',
source_title TEXT NOT NULL DEFAULT '',
target_platform TEXT NOT NULL DEFAULT 'youtube',
youtube_key_suffix TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'active',
started_at REAL NOT NULL,
ended_at REAL,
duration_seconds REAL NOT NULL DEFAULT 0,
last_seen_at REAL NOT NULL,
created_at REAL NOT NULL,
updated_at REAL NOT NULL,
quality_score INTEGER NOT NULL DEFAULT 0,
viewer_peak INTEGER NOT NULL DEFAULT 0,
last_viewer_count INTEGER,
last_live_status TEXT NOT NULL DEFAULT '',
last_health TEXT NOT NULL DEFAULT '',
last_popup_text TEXT NOT NULL DEFAULT '',
last_page_url TEXT NOT NULL DEFAULT '',
last_page_title TEXT NOT NULL DEFAULT '',
control_actions_json TEXT NOT NULL DEFAULT '[]',
tags_json TEXT NOT NULL DEFAULT '[]',
snapshot_json TEXT NOT NULL DEFAULT '{}'
)
"""
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS youtube_live_samples (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_id INTEGER NOT NULL,
ts REAL NOT NULL,
source TEXT NOT NULL DEFAULT '',
live_status TEXT NOT NULL DEFAULT '',
viewer_count INTEGER,
like_count INTEGER,
chat_rate REAL,
health TEXT NOT NULL DEFAULT '',
popup_text TEXT NOT NULL DEFAULT '',
page_url TEXT NOT NULL DEFAULT '',
page_title TEXT NOT NULL DEFAULT '',
payload_json TEXT NOT NULL DEFAULT '{}',
FOREIGN KEY(event_id) REFERENCES youtube_live_events(id) ON DELETE CASCADE
)
"""
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS youtube_live_alerts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_id INTEGER NOT NULL,
ts REAL NOT NULL,
severity TEXT NOT NULL DEFAULT 'info',
title TEXT NOT NULL DEFAULT '',
message TEXT NOT NULL DEFAULT '',
source TEXT NOT NULL DEFAULT '',
fingerprint TEXT NOT NULL DEFAULT '',
payload_json TEXT NOT NULL DEFAULT '{}',
FOREIGN KEY(event_id) REFERENCES youtube_live_events(id) ON DELETE CASCADE
)
"""
)
conn.execute("CREATE INDEX IF NOT EXISTS idx_youtube_live_events_status ON youtube_live_events(status, updated_at DESC)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_youtube_live_events_process ON youtube_live_events(process, updated_at DESC)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_youtube_live_samples_event ON youtube_live_samples(event_id, ts DESC)")
conn.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_youtube_live_alert_fingerprint "
"ON youtube_live_alerts(event_id, fingerprint)"
)
conn.commit()
_chmod_runtime_files(path)
return conn
def _json_dumps(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), default=str)
def _json_loads(raw: str | None, fallback: Any) -> Any:
if not raw:
return fallback
try:
return json.loads(raw)
except json.JSONDecodeError:
return fallback
def _row_to_event(row: sqlite3.Row) -> dict[str, Any]:
data = dict(row)
data["control_actions"] = _json_loads(data.pop("control_actions_json", "[]"), [])
data["tags"] = _json_loads(data.pop("tags_json", "[]"), [])
data["snapshot"] = _json_loads(data.pop("snapshot_json", "{}"), {})
if data.get("ended_at"):
data["duration_seconds"] = int(float(data.get("duration_seconds") or 0))
else:
data["duration_seconds"] = int(max(0, time.time() - float(data.get("started_at") or time.time())))
return data
def _row_to_sample(row: sqlite3.Row) -> dict[str, Any]:
data = dict(row)
data["payload"] = _json_loads(data.pop("payload_json", "{}"), {})
return data
def _row_to_alert(row: sqlite3.Row) -> dict[str, Any]:
data = dict(row)
data["payload"] = _json_loads(data.pop("payload_json", "{}"), {})
return data
def extract_source_room_id(*values: str | None) -> str:
for value in values:
text = str(value or "")
match = _DOUYIN_ROOM_RE.search(text)
if match:
return match.group(1)
match = _ROOM_HINT_RE.search(text)
if match:
return match.group(1)
return ""
def extract_first_url(text: str | None) -> str:
for line in str(text or "").splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
match = _URL_RE.search(stripped)
if match:
return match.group(0).rstrip(";,")
match = _URL_RE.search(str(text or ""))
return match.group(0).rstrip(";,") if match else ""
def extract_youtube_key_suffix(text: str | None) -> str:
match = _KEY_RE.search(str(text or ""))
if not match:
return ""
key = match.group(1).strip()
if not key:
return ""
return key[-6:] if len(key) > 6 else key
def _normalize_process(value: str | None) -> str:
cleaned = re.sub(r"[^A-Za-z0-9_.:-]+", "_", str(value or "").strip())
return cleaned[:96] or "youtube"
def _status_from_payload(payload: dict[str, Any]) -> str:
raw = " ".join(
str(payload.get(key) or "")
for key in ("live_status", "status", "business_status", "process_status", "health", "page_title")
).lower()
if any(token in raw for token in ("error", "failed", "断开", "异常", "错误")):
return "error"
if any(token in raw for token in ("live", "streaming", "excellent", "healthy", "直播中", "已开始", "正在直播")):
return "active"
if any(token in raw for token in ("waiting", "idle", "offline", "stopped", "等待", "未开始", "停止")):
return "idle"
return "active"
def _quality_score(payload: dict[str, Any]) -> int:
score = 60
raw = " ".join(str(payload.get(key) or "") for key in ("live_status", "health", "business_status", "process_status")).lower()
if any(token in raw for token in ("excellent", "healthy", "streaming", "直播中", "良好")):
score += 25
if any(token in raw for token in ("warning", "unstable", "poor", "buffer", "警告", "不佳", "卡顿")):
score -= 20
if any(token in raw for token in ("error", "failed", "disconnect", "异常", "错误", "断开")):
score -= 35
viewers = _coerce_int(payload.get("viewer_count"))
if viewers and viewers > 0:
score += min(10, viewers // 10 + 1)
return max(0, min(100, score))
def _coerce_int(value: Any) -> int | None:
if value is None or value == "":
return None
if isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return max(0, int(value))
text = str(value).strip().replace(",", "")
match = re.search(r"\d+", text)
if not match:
return None
return max(0, int(match.group(0)))
def _action_history(row: sqlite3.Row | None, action: str, ts: float, note: str = "") -> str:
current = _json_loads(row["control_actions_json"] if row else "[]", [])
if not isinstance(current, list):
current = []
current.append({"action": action, "ts": ts, "note": note})
return _json_dumps(current[-80:])
def _active_event_row(
conn: sqlite3.Connection,
*,
process: str,
source_room_id: str = "",
source_url: str = "",
) -> sqlite3.Row | None:
if source_room_id:
row = conn.execute(
"""
SELECT * FROM youtube_live_events
WHERE ended_at IS NULL AND status IN ('active', 'error') AND source_room_id = ?
ORDER BY updated_at DESC LIMIT 1
""",
(source_room_id,),
).fetchone()
if row:
return row
if source_url:
row = conn.execute(
"""
SELECT * FROM youtube_live_events
WHERE ended_at IS NULL AND status IN ('active', 'error') AND source_url = ?
ORDER BY updated_at DESC LIMIT 1
""",
(source_url,),
).fetchone()
if row:
return row
return conn.execute(
"""
SELECT * FROM youtube_live_events
WHERE ended_at IS NULL AND status IN ('active', 'error') AND process = ?
ORDER BY updated_at DESC LIMIT 1
""",
(process,),
).fetchone()
def _upsert_event(
conn: sqlite3.Connection,
*,
process: str,
mode: str = "",
channel_id: str = "",
channel_name: str = "",
source_url: str = "",
source_room_id: str = "",
source_title: str = "",
youtube_key_suffix: str = "",
payload: dict[str, Any] | None = None,
action: str = "observe",
note: str = "",
) -> sqlite3.Row:
now = time.time()
process = _normalize_process(process)
payload = payload or {}
source_room_id = source_room_id or extract_source_room_id(source_url, source_title, payload.get("page_title"), payload.get("text"))
source_url = source_url or extract_first_url(str(payload.get("url") or ""))
live_status = str(payload.get("live_status") or payload.get("business_status") or payload.get("status") or "")
health = str(payload.get("health") or "")
page_url = str(payload.get("url") or payload.get("page_url") or "")
page_title = str(payload.get("page_title") or payload.get("title") or "")
popup_text = _primary_popup(payload)
viewer_count = _coerce_int(payload.get("viewer_count"))
score = _quality_score(payload)
status = _status_from_payload(payload)
row = _active_event_row(conn, process=process, source_room_id=source_room_id, source_url=source_url)
snapshot = {
"last_payload": payload,
"source_room_id": source_room_id,
"source_url": source_url,
"source_title": source_title,
"updated_at": now,
}
if row:
conn.execute(
"""
UPDATE youtube_live_events
SET mode = COALESCE(NULLIF(?, ''), mode),
channel_id = COALESCE(NULLIF(?, ''), channel_id),
channel_name = COALESCE(NULLIF(?, ''), channel_name),
source_url = COALESCE(NULLIF(?, ''), source_url),
source_room_id = COALESCE(NULLIF(?, ''), source_room_id),
source_title = COALESCE(NULLIF(?, ''), source_title),
youtube_key_suffix = COALESCE(NULLIF(?, ''), youtube_key_suffix),
status = CASE WHEN ? = 'idle' THEN status ELSE ? END,
last_seen_at = ?,
updated_at = ?,
quality_score = ?,
viewer_peak = CASE
WHEN ? IS NOT NULL AND ? > viewer_peak THEN ?
ELSE viewer_peak
END,
last_viewer_count = COALESCE(?, last_viewer_count),
last_live_status = COALESCE(NULLIF(?, ''), last_live_status),
last_health = COALESCE(NULLIF(?, ''), last_health),
last_popup_text = COALESCE(NULLIF(?, ''), last_popup_text),
last_page_url = COALESCE(NULLIF(?, ''), last_page_url),
last_page_title = COALESCE(NULLIF(?, ''), last_page_title),
control_actions_json = ?,
snapshot_json = ?
WHERE id = ?
""",
(
mode,
channel_id,
channel_name,
source_url,
source_room_id,
source_title,
youtube_key_suffix,
status,
status,
now,
now,
score,
viewer_count,
viewer_count,
viewer_count,
viewer_count,
live_status,
health,
popup_text,
page_url,
page_title,
_action_history(row, action, now, note),
_json_dumps(snapshot),
row["id"],
),
)
event_id = int(row["id"])
else:
conn.execute(
"""
INSERT INTO youtube_live_events(
event_uuid, process, mode, channel_id, channel_name, source_url, source_room_id, source_title,
youtube_key_suffix, status, started_at, last_seen_at, created_at, updated_at, quality_score,
viewer_peak, last_viewer_count, last_live_status, last_health, last_popup_text,
last_page_url, last_page_title, control_actions_json, snapshot_json
)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
""",
(
str(uuid.uuid4()),
process,
mode,
channel_id,
channel_name,
source_url,
source_room_id,
source_title,
youtube_key_suffix,
"active" if status == "idle" else status,
now,
now,
now,
now,
score,
viewer_count or 0,
viewer_count,
live_status,
health,
popup_text,
page_url,
page_title,
_action_history(None, action, now, note),
_json_dumps(snapshot),
),
)
event_id = int(conn.execute("SELECT last_insert_rowid()").fetchone()[0])
row = conn.execute("SELECT * FROM youtube_live_events WHERE id = ?", (event_id,)).fetchone()
assert row is not None
return row
def _primary_popup(payload: dict[str, Any]) -> str:
raw = payload.get("popups") or payload.get("dialogs") or payload.get("alerts") or []
if isinstance(raw, str):
return raw.strip()[:500]
if isinstance(raw, list):
texts = [str(item).strip() for item in raw if str(item).strip()]
return " | ".join(texts)[:500]
return ""
def _payload_indicates_process_inactive(payload: dict[str, Any]) -> bool:
if bool(payload.get("is_pushing")) or bool(payload.get("ffmpeg_active")):
return False
process_status = str(payload.get("process_status") or "").strip().lower()
business_status = str(payload.get("business_status") or "").strip().lower()
raw = " ".join(
str(payload.get(key) or "")
for key in ("raw_status", "business_note", "recent_log", "recent_error", "live_status", "status")
).lower()
if any(token in raw for token in ("starting", "launching", "restarting", "\u542f\u52a8\u4e2d", "\u91cd\u542f\u4e2d")):
return False
stopped_process = {
"configured",
"disabled",
"idle",
"missing",
"not_running",
"ready",
"stopped",
"unknown",
}
stopped_business = {"configured", "idle", "not_running", "ready", "stopped", "unknown"}
if process_status in stopped_process:
return True
if business_status in stopped_business and payload.get("is_pushing") is False:
return True
if payload.get("is_pushing") is False and payload.get("ffmpeg_active") is False and any(
token in raw
for token in (
"not running",
"not started",
"configured but",
"process is configured",
"\u672a\u542f\u52a8",
"\u672a\u8fd0\u884c",
"\u5f53\u524d\u672a\u542f\u52a8",
)
):
return True
return False
def _insert_sample(conn: sqlite3.Connection, event_id: int, payload: dict[str, Any], source: str) -> None:
popup_text = _primary_popup(payload)
conn.execute(
"""
INSERT INTO youtube_live_samples(
event_id, ts, source, live_status, viewer_count, like_count, chat_rate, health,
popup_text, page_url, page_title, payload_json
)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)
""",
(
event_id,
float(payload.get("captured_at") or time.time()),
source,
str(payload.get("live_status") or payload.get("business_status") or payload.get("status") or ""),
_coerce_int(payload.get("viewer_count")),
_coerce_int(payload.get("like_count")),
float(payload.get("chat_rate") or 0) if payload.get("chat_rate") not in (None, "") else None,
str(payload.get("health") or ""),
popup_text,
str(payload.get("url") or payload.get("page_url") or ""),
str(payload.get("page_title") or payload.get("title") or ""),
_json_dumps(payload),
),
)
def _insert_alerts(conn: sqlite3.Connection, event_id: int, payload: dict[str, Any], source: str) -> None:
popup_text = _primary_popup(payload)
messages: list[tuple[str, str, str]] = []
if popup_text:
messages.append(("warning", "Browser popup", popup_text))
health = str(payload.get("health") or "")
if health and any(token in health.lower() for token in ("error", "warning", "poor", "unstable", "异常", "错误", "警告", "不佳")):
messages.append(("warning", "Stream health", health))
live_status = str(payload.get("live_status") or "")
if live_status and any(token in live_status.lower() for token in ("error", "failed", "异常", "错误")):
messages.append(("critical", "Live status", live_status))
for severity, title, message in messages:
fingerprint = hashlib.sha1(f"{event_id}|{title}|{message[:240]}".encode("utf-8", "ignore")).hexdigest()
conn.execute(
"""
INSERT OR IGNORE INTO youtube_live_alerts(event_id, ts, severity, title, message, source, fingerprint, payload_json)
VALUES(?,?,?,?,?,?,?,?)
""",
(event_id, time.time(), severity, title, message[:1000], source, fingerprint, _json_dumps(payload)),
)
def record_control_action(
process: str,
action: str,
*,
script: str = "",
url_lines: str = "",
youtube_ini_text: str = "",
channel_id: str = "",
channel_name: str = "",
mode: str = "",
note: str = "",
db_path: Path | None = None,
) -> dict[str, Any]:
source_url = extract_first_url(url_lines)
source_room_id = extract_source_room_id(url_lines)
payload = {
"source": "control",
"status": "active",
"process_status": "running",
"script": script,
"action": action,
}
conn = _connect(db_path)
try:
if action in {"stop", "finish", "end"}:
return finish_active_events(process, reason=note or action, db_path=db_path)
if action == "restart":
finish_active_events(process, reason="restart", db_path=db_path)
row = _upsert_event(
conn,
process=process,
mode=mode,
channel_id=channel_id,
channel_name=channel_name,
source_url=source_url,
source_room_id=source_room_id,
youtube_key_suffix=extract_youtube_key_suffix(youtube_ini_text),
payload=payload,
action=action,
note=note,
)
_insert_sample(conn, int(row["id"]), payload, "control")
conn.commit()
return {"event": _row_to_event(row)}
finally:
conn.close()
def record_process_observation(
process: str,
payload: dict[str, Any],
*,
url_lines: str = "",
db_path: Path | None = None,
) -> dict[str, Any]:
if _payload_indicates_process_inactive(payload):
return finish_active_events(process, reason=str(payload.get("business_note") or payload.get("raw_status") or "process inactive"), db_path=db_path)
source_url = extract_first_url(url_lines)
source_room_id = extract_source_room_id(url_lines, payload.get("recent_log"), payload.get("recent_error"))
conn = _connect(db_path)
try:
row = _upsert_event(
conn,
process=process,
source_url=source_url,
source_room_id=source_room_id,
payload=payload,
action="process_observe",
)
event_id = int(row["id"])
last = conn.execute("SELECT ts FROM youtube_live_samples WHERE event_id = ? ORDER BY ts DESC LIMIT 1", (event_id,)).fetchone()
if not last or time.time() - float(last["ts"]) >= 5:
_insert_sample(conn, event_id, payload, "process")
conn.commit()
return {"event": _row_to_event(conn.execute("SELECT * FROM youtube_live_events WHERE id = ?", (event_id,)).fetchone())}
finally:
conn.close()
def ingest_browser_telemetry(payload: dict[str, Any], *, db_path: Path | None = None) -> dict[str, Any]:
process = _normalize_process(str(payload.get("process") or payload.get("lane") or "chrome_extension"))
source_url = str(payload.get("source_url") or "") or extract_first_url(
" ".join(str(payload.get(key) or "") for key in ("url", "page_title", "text", "source_text"))
)
source_room_id = str(payload.get("source_room_id") or "") or extract_source_room_id(
source_url,
payload.get("url"),
payload.get("page_title"),
payload.get("text"),
payload.get("source_text"),
)
conn = _connect(db_path)
try:
row = _upsert_event(
conn,
process=process,
mode=str(payload.get("mode") or "browser"),
channel_id=str(payload.get("channel_id") or ""),
channel_name=str(payload.get("channel_name") or ""),
source_url=source_url,
source_room_id=source_room_id,
source_title=str(payload.get("source_title") or payload.get("stream_title") or ""),
payload=payload,
action="browser_telemetry",
note=str(payload.get("url") or ""),
)
event_id = int(row["id"])
_insert_sample(conn, event_id, payload, str(payload.get("source") or "chrome_extension"))
_insert_alerts(conn, event_id, payload, str(payload.get("source") or "chrome_extension"))
prune_old_samples(conn)
conn.commit()
return {
"message": "telemetry stored",
"event": _row_to_event(conn.execute("SELECT * FROM youtube_live_events WHERE id = ?", (event_id,)).fetchone()),
}
finally:
conn.close()
def finish_active_events(process: str | None = None, *, reason: str = "manual", db_path: Path | None = None) -> dict[str, Any]:
now = time.time()
conn = _connect(db_path)
try:
if process:
rows = conn.execute(
"SELECT * FROM youtube_live_events WHERE ended_at IS NULL AND process = ?",
(_normalize_process(process),),
).fetchall()
else:
rows = conn.execute("SELECT * FROM youtube_live_events WHERE ended_at IS NULL").fetchall()
closed: list[dict[str, Any]] = []
for row in rows:
duration = max(0, now - float(row["started_at"]))
conn.execute(
"""
UPDATE youtube_live_events
SET ended_at = ?, duration_seconds = ?, status = 'ended', updated_at = ?,
control_actions_json = ?
WHERE id = ?
""",
(now, int(duration), now, _action_history(row, "finish", now, reason), int(row["id"])),
)
closed.append(_row_to_event(conn.execute("SELECT * FROM youtube_live_events WHERE id = ?", (int(row["id"]),)).fetchone()))
conn.commit()
return {"message": "events closed", "count": len(closed), "events": closed}
finally:
conn.close()
def list_live_events(
*,
status: str = "",
process: str = "",
limit: int = 50,
offset: int = 0,
db_path: Path | None = None,
) -> dict[str, Any]:
clauses: list[str] = []
params: list[Any] = []
if status:
if status == "active":
clauses.append("ended_at IS NULL")
else:
clauses.append("status = ?")
params.append(status)
if process:
clauses.append("process = ?")
params.append(_normalize_process(process))
where = "WHERE " + " AND ".join(clauses) if clauses else ""
safe_limit = max(1, min(int(limit), 200))
safe_offset = max(0, int(offset))
conn = _connect(db_path)
try:
rows = conn.execute(
f"SELECT * FROM youtube_live_events {where} ORDER BY updated_at DESC LIMIT ? OFFSET ?",
(*params, safe_limit, safe_offset),
).fetchall()
total = conn.execute(f"SELECT COUNT(*) FROM youtube_live_events {where}", params).fetchone()[0]
return {"events": [_row_to_event(row) for row in rows], "total": int(total), "limit": safe_limit, "offset": safe_offset}
finally:
conn.close()
def get_live_event(event_id: int | str, *, db_path: Path | None = None) -> dict[str, Any]:
conn = _connect(db_path)
try:
row = conn.execute("SELECT * FROM youtube_live_events WHERE id = ? OR event_uuid = ?", (event_id, str(event_id))).fetchone()
if not row:
return {}
samples = conn.execute(
"SELECT * FROM youtube_live_samples WHERE event_id = ? ORDER BY ts DESC LIMIT 240",
(int(row["id"]),),
).fetchall()
alerts = conn.execute(
"SELECT * FROM youtube_live_alerts WHERE event_id = ? ORDER BY ts DESC LIMIT 120",
(int(row["id"]),),
).fetchall()
event = _row_to_event(row)
event["samples"] = [_row_to_sample(item) for item in samples]
event["alerts"] = [_row_to_alert(item) for item in alerts]
event["sample_count"] = int(conn.execute("SELECT COUNT(*) FROM youtube_live_samples WHERE event_id = ?", (int(row["id"]),)).fetchone()[0])
return event
finally:
conn.close()
def youtube_live_summary(*, db_path: Path | None = None) -> dict[str, Any]:
conn = _connect(db_path)
try:
active_rows = conn.execute(
"SELECT * FROM youtube_live_events WHERE ended_at IS NULL ORDER BY updated_at DESC LIMIT 12"
).fetchall()
latest_rows = conn.execute("SELECT * FROM youtube_live_events ORDER BY updated_at DESC LIMIT 16").fetchall()
alert_rows = conn.execute("SELECT * FROM youtube_live_alerts ORDER BY ts DESC LIMIT 20").fetchall()
total = int(conn.execute("SELECT COUNT(*) FROM youtube_live_events").fetchone()[0])
ended = int(conn.execute("SELECT COUNT(*) FROM youtube_live_events WHERE ended_at IS NOT NULL").fetchone()[0])
sample_count = int(conn.execute("SELECT COUNT(*) FROM youtube_live_samples").fetchone()[0])
total_duration = int(conn.execute("SELECT COALESCE(SUM(duration_seconds),0) FROM youtube_live_events").fetchone()[0] or 0)
active = [_row_to_event(row) for row in active_rows]
latest = [_row_to_event(row) for row in latest_rows]
return {
"active": active,
"latest": latest,
"alerts": [_row_to_alert(row) for row in alert_rows],
"stats": {
"total_events": total,
"ended_events": ended,
"active_events": len(active),
"sample_count": sample_count,
"total_duration_seconds": total_duration,
"viewer_peak": max([int(item.get("viewer_peak") or 0) for item in latest] or [0]),
},
"capabilities": [
"event_db",
"event_detail",
"source_room_trace",
"duration_trace",
"browser_extension_telemetry",
"viewer_count_capture",
"live_status_capture",
"popup_alert_capture",
"health_score",
"process_control_audit",
"sample_timeline",
"multi_lane_history",
"tampermonkey_compat",
],
}
finally:
conn.close()
def close_live_event(event_id: int | str, *, reason: str = "manual", db_path: Path | None = None) -> dict[str, Any]:
event = get_live_event(event_id, db_path=db_path)
if not event:
return {}
if event.get("ended_at"):
return {"event": event, "message": "already closed"}
now = time.time()
duration = max(0, now - float(event["started_at"]))
conn = _connect(db_path)
try:
row = conn.execute("SELECT * FROM youtube_live_events WHERE id = ?", (int(event["id"]),)).fetchone()
conn.execute(
"""
UPDATE youtube_live_events
SET ended_at = ?, duration_seconds = ?, status = 'ended', updated_at = ?,
control_actions_json = ?
WHERE id = ?
""",
(now, int(duration), now, _action_history(row, "close", now, reason), int(event["id"])),
)
conn.commit()
return {"message": "event closed", "event": get_live_event(event_id, db_path=db_path)}
finally:
conn.close()
def prune_old_samples(conn: sqlite3.Connection, *, keep_days: int = 14, keep_per_event: int = 2000) -> None:
cutoff = time.time() - max(1, keep_days) * 86400
conn.execute("DELETE FROM youtube_live_samples WHERE ts < ?", (cutoff,))
event_ids = [int(row[0]) for row in conn.execute("SELECT id FROM youtube_live_events ORDER BY updated_at DESC LIMIT 200").fetchall()]
for event_id in event_ids:
conn.execute(
"""
DELETE FROM youtube_live_samples
WHERE event_id = ?
AND id NOT IN (
SELECT id FROM youtube_live_samples WHERE event_id = ? ORDER BY ts DESC LIMIT ?
)
""",
(event_id, event_id, keep_per_event),
)

View File

@ -12,7 +12,8 @@ _ANY_HEADER = re.compile(r"^\s*\[[^\]]+\]\s*$")
_KEY_LINE = re.compile(r"^\s*(?:key|stream_key)\s*=", re.IGNORECASE)
_YOUTUBE_PRO_PM2_PREFIX = "youtube2__"
_RESERVED_PM2_NAMES = frozenset({"youtube", "douyin_youtube", "tiktok", "obs", "web"})
_DEFAULT_YOUTUBE_TEMPLATE = "[youtube]\nkey = \nrtmps = 是\nfast_audio = 0\n"
_DEFAULT_YOUTUBE_TEMPLATE = "[youtube]\nkey = \nrtmps = 是\nfast_audio = 1\n"
_BROKEN_LANE_NAME_RE = re.compile(r"(?:\?|\uff1f){2,}|\ufffd|锟|绾胯矾|çº|è·|Â", re.IGNORECASE)
def sanitize_pm2_segment(value: str) -> str:
@ -40,6 +41,20 @@ def channel_pm2_name(channel: dict[str, Any]) -> str:
)
def is_broken_youtube_pro_lane_name(value: str) -> bool:
s = (value or "").strip()
return not s or s.lower() in {"undefined", "null", "nan"} or bool(_BROKEN_LANE_NAME_RE.search(s))
def clean_youtube_pro_lane_name(value: str, index: int) -> str:
raw = (value or "").strip()
if not is_broken_youtube_pro_lane_name(raw):
return raw
match = re.search(r"\d+", raw)
lane_no = match.group(0) if match else str(max(0, index) + 1)
return f"线路 {lane_no}"
def managed_url_config_relpath_for_pm2(pm2: str) -> str:
return f"URL_config.{sanitize_pm2_segment(pm2)}.ini"
@ -52,7 +67,7 @@ def normalize_youtube_pro_channels(channels: Iterable[Any]) -> list[dict[str, An
out: list[dict[str, Any]] = []
seen_ids: set[str] = set()
seen_pm2: set[str] = set()
for item in channels:
for index, item in enumerate(channels):
if not isinstance(item, dict):
raise ValueError("each channel must be an object")
row = dict(item)
@ -64,7 +79,7 @@ def normalize_youtube_pro_channels(channels: Iterable[Any]) -> list[dict[str, An
seen_ids.add(cid)
row["id"] = cid
row["name"] = str(row.get("name", "")).strip() or cid
row["name"] = clean_youtube_pro_lane_name(str(row.get("name", "")), index)
pm2 = channel_pm2_name(row)
if not pm2:
raise ValueError(f"channel.pm2Name invalid for {cid}")
@ -187,7 +202,7 @@ def _upsert_youtube_key(text: str, stream_key: str) -> str:
"[youtube]",
f"key = {stream_key}",
f"rtmps = {_rtmps_value_for_key(stream_key)}",
"fast_audio = 0",
"fast_audio = 1",
"",
]
tail = source.strip("\n")

View File

@ -0,0 +1,209 @@
from __future__ import annotations
import re
import time
from typing import Any
from src.douyin_source_display import extract_douyin_source_meta
_FFMPEG_KV_RE = re.compile(r"(?P<key>frame|fps|bitrate|speed|drop|dup)\s*=\s*(?P<value>[^\s]+)", re.IGNORECASE)
_TIME_RE = re.compile(r"time\s*=\s*(?P<value>\d{2}:\d{2}:\d{2}(?:\.\d+)?)", re.IGNORECASE)
_URL_RE = re.compile(r"https?://[^\s\"'<>]+", re.IGNORECASE)
def _as_float(value: Any) -> float | None:
text = str(value or "").strip().lower().replace("x", "").replace("kbits/s", "").replace("kb/s", "")
text = text.replace(",", "")
match = re.search(r"-?\d+(?:\.\d+)?", text)
if not match:
return None
try:
return float(match.group(0))
except ValueError:
return None
def _as_int(value: Any) -> int | None:
parsed = _as_float(value)
return None if parsed is None else max(0, int(parsed))
def parse_ffmpeg_metrics(*texts: str) -> dict[str, Any]:
raw = "\n".join(str(item or "") for item in texts)
tail = raw[-16000:]
metrics: dict[str, Any] = {}
for match in _FFMPEG_KV_RE.finditer(tail):
key = match.group("key").lower()
value = match.group("value")
if key in {"frame", "drop", "dup"}:
metrics[key] = _as_int(value)
elif key in {"fps", "speed", "bitrate"}:
metrics[key] = _as_float(value)
time_match = None
for time_match in _TIME_RE.finditer(tail):
pass
if time_match:
metrics["encoded_time"] = time_match.group("value")
lower = tail.lower()
metrics["error_count"] = sum(
lower.count(token)
for token in (
"error",
"failed",
"connection refused",
"timed out",
"server returned",
"broken pipe",
"invalid data",
"non-monotonous dts",
"too many packets buffered",
)
)
metrics["reconnect_count"] = sum(lower.count(token) for token in ("reconnect", "retry", "connection reset"))
return metrics
def _count_urls(text: str) -> int:
return len(_URL_RE.findall(str(text or "")))
def _ini_has_enabled_rtmps(text: str) -> bool:
lower = str(text or "").lower()
return any(token in lower for token in ("rtmps = 是", "rtmps=true", "rtmps = true", "rtmps=1", "rtmps = 1"))
def _ini_has_key(text: str) -> bool:
return bool(re.search(r"^\s*key\s*=\s*\S+", str(text or ""), re.IGNORECASE | re.MULTILINE))
def _process_score(row: dict[str, Any], metrics: dict[str, Any]) -> tuple[int, list[dict[str, str]]]:
score = 100
issues: list[dict[str, str]] = []
if not row.get("ffmpeg_active") and not row.get("is_pushing"):
score -= 35
issues.append({"level": "critical", "text": "FFmpeg 未检测到推流进程"})
if not row.get("is_pushing"):
score -= 25
issues.append({"level": "critical", "text": "当前没有稳定推流输出"})
speed = metrics.get("speed")
if isinstance(speed, (int, float)) and speed < 0.98:
score -= 18
issues.append({"level": "warning", "text": f"编码速度 {speed:.2f}x,低于实时直播要求"})
fps = metrics.get("fps")
if isinstance(fps, (int, float)) and fps > 0 and fps < 24:
score -= 10
issues.append({"level": "warning", "text": f"帧率偏低:{fps:.1f} fps"})
if int(metrics.get("error_count") or 0) > 0:
score -= min(30, int(metrics.get("error_count") or 0) * 6)
issues.append({"level": "warning", "text": "日志出现 FFmpeg/网络错误"})
if int(metrics.get("reconnect_count") or 0) > 2:
score -= 10
issues.append({"level": "warning", "text": "源站或网络发生多次重连"})
if not issues and row.get("is_pushing"):
issues.append({"level": "ok", "text": "推流链路正常,保持稳定即可"})
return max(0, min(100, score)), issues
def build_youtube_quality_guard_report(
rows: list[dict[str, Any]],
*,
live_summary: dict[str, Any] | None = None,
config_by_process: dict[str, dict[str, str]] | None = None,
) -> dict[str, Any]:
live_summary = live_summary or {}
config_by_process = config_by_process or {}
lanes: list[dict[str, Any]] = []
recommendations: list[dict[str, str]] = []
for row in rows:
process = str(row.get("pm2") or row.get("process") or "")
metrics = parse_ffmpeg_metrics(str(row.get("recent_log") or ""), str(row.get("recent_error") or ""))
score, issues = _process_score(row, metrics)
cfg = config_by_process.get(process) or {}
source_meta = extract_douyin_source_meta(cfg.get("url_lines", ""), str(row.get("recent_log") or ""))
source_title = str(row.get("source_title") or source_meta.get("source_title") or "").strip()
source_room_id = str(row.get("source_room_id") or source_meta.get("source_room_id") or "").strip()
source_url = str(row.get("source_url") or source_meta.get("source_url") or "").strip()
source_display = str(
row.get("source_display")
or source_meta.get("source_display")
or source_title
or (f"抖音直播间 {source_room_id}" if source_room_id else "")
).strip()
url_count = _count_urls(cfg.get("url_lines", ""))
has_key = _ini_has_key(cfg.get("youtube_ini_text", ""))
rtmps = _ini_has_enabled_rtmps(cfg.get("youtube_ini_text", ""))
if not has_key:
score = max(0, score - 30)
issues.append({"level": "critical", "text": "YouTube 推流 key 未配置"})
if not rtmps:
score = max(0, score - 8)
issues.append({"level": "warning", "text": "建议使用 RTMPS 推流"})
if url_count == 0:
score = max(0, score - 15)
issues.append({"level": "warning", "text": "没有配置转播源 URL"})
lanes.append(
{
"process": process,
"label": row.get("label") or process,
"source_title": source_title,
"source_room_id": source_room_id,
"source_url": source_url,
"source_display": source_display,
"status": row.get("business_status") or row.get("process_status") or "",
"is_pushing": bool(row.get("is_pushing")),
"ffmpeg_active": bool(row.get("ffmpeg_active")),
"score": score,
"metrics": metrics,
"url_count": url_count,
"rtmps": rtmps,
"has_stream_key": has_key,
"issues": issues[:6],
}
)
active_events = int(((live_summary.get("stats") or {}).get("active_events") or len(live_summary.get("active") or [])) or 0)
sample_count = int(((live_summary.get("stats") or {}).get("sample_count") or 0) or 0)
viewer_peak = int(((live_summary.get("stats") or {}).get("viewer_peak") or 0) or 0)
pushing_count = sum(1 for lane in lanes if lane["is_pushing"])
score = int(sum(lane["score"] for lane in lanes) / len(lanes)) if lanes else 0
if pushing_count == 0:
recommendations.append({"level": "critical", "text": "没有正在推流的 YouTube 线路;推荐系统首先需要稳定不断流的直播信号"})
if active_events == 0 and pushing_count > 0:
recommendations.append({"level": "warning", "text": "推流已存在但事件中心未形成活动事件,检查状态采集/Chrome 插件"})
if sample_count == 0:
recommendations.append({"level": "warning", "text": "没有 Studio 页面采样;请在 Neko 打开 YouTube Studio 并保持插件启用"})
if all(lane.get("rtmps") for lane in lanes) and lanes:
recommendations.append({"level": "ok", "text": "RTMPS 已启用,适合长期稳定直播"})
if viewer_peak > 0:
recommendations.append({"level": "ok", "text": f"已采集到观众峰值 {viewer_peak},数据闭环正常"})
return {
"generated_at": time.time(),
"score": max(0, min(100, score)),
"summary": {
"lanes": len(lanes),
"pushing_lanes": pushing_count,
"active_events": active_events,
"sample_count": sample_count,
"viewer_peak": viewer_peak,
},
"lanes": lanes,
"recommendations": recommendations[:10],
"ffmpeg_profile": {
"target": "1080p30/RTMPS/AAC/stable input copy when possible",
"guardrails": [
"保持 speed >= 1.00x",
"长直播优先稳定码率与低错误率,而不是频繁重启",
"Studio 弹窗、健康度、观众数必须持续采样",
"源直播间断流时自动记录事件并提示切换备用 URL",
],
},
}

View File

@ -1,9 +1,10 @@
from __future__ import annotations
import unittest
import asyncio
import tempfile
from pathlib import Path
from unittest.mock import patch
from unittest.mock import AsyncMock, patch
import yaml
@ -12,6 +13,7 @@ from src.control_plane import (
_normalize_shellcrash_yaml,
deployment_report,
network_iface_stats,
neko_instance_action,
stack_summary,
)
@ -27,11 +29,16 @@ class ControlPlaneServiceTests(unittest.TestCase):
"pulseaudio",
"kmscube",
"openclaw",
"homeassistant",
"frigate",
"wol",
"ntfy",
"coturn",
}.issubset(ids)
)
def test_stack_summary_exposes_new_quick_links(self) -> None:
env = {"HOSTNAME_ALIAS": "live", "NEKO_WIREGUARD_HOST": "10.88.0.2"}
env = {"HOSTNAME_ALIAS": "live", "NEKO_ACCESS_MODE": "remote", "NEKO_WIREGUARD_HOST": "10.88.0.2"}
with patch("src.control_plane.load_stack_env", return_value=env):
with patch("src.control_plane.local_ips", return_value=["192.168.2.20"]):
summary = stack_summary()
@ -42,6 +49,14 @@ class ControlPlaneServiceTests(unittest.TestCase):
"uptime_kuma",
"pulseaudio_tcp",
"openclaw",
"studio",
"youtube_events",
"homeassistant",
"frigate",
"wol",
"ntfy",
"coturn_turn",
"coturn_turns",
"neko_browser",
"neko_browser_1",
"neko_browser_2",
@ -56,6 +71,23 @@ class ControlPlaneServiceTests(unittest.TestCase):
self.assertEqual(links["neko_browser"], "http://10.88.0.2:9200")
self.assertEqual(links["neko_browser_wireguard_1"], "http://10.88.0.2:9200")
self.assertEqual(links["neko_browser_mdns_1"], "http://live.local:9200")
self.assertEqual(links["homeassistant"], "http://live.local:8123")
self.assertEqual(links["frigate"], "http://live.local:5001")
self.assertEqual(links["ntfy"], "http://live.local:8089")
self.assertEqual(links["coturn_turn"], "turn:live.local:3478?transport=udp")
self.assertEqual(links["coturn_turns"], "turns:live.local:5349?transport=tcp")
self.assertTrue(links["wol"].endswith("/?view=studio"))
self.assertTrue(links["youtube_events"].endswith("/youtube-events"))
def test_stack_summary_keeps_neko_on_lan_until_remote_mode_selected(self) -> None:
env = {"HOSTNAME_ALIAS": "live", "NEKO_WIREGUARD_HOST": "10.88.0.2"}
with patch("src.control_plane.load_stack_env", return_value=env):
with patch("src.control_plane.local_ips", return_value=["192.168.2.20"]):
summary = stack_summary()
links = summary["quick_links"]
self.assertNotIn("neko_browser_wireguard_1", links)
self.assertEqual(links["neko_browser"], "http://live.local:9200")
self.assertEqual(links["neko_browser_lan_1"], "http://192.168.2.20:9200")
def test_stack_summary_exposes_pro_neko_links_when_configured(self) -> None:
with patch("src.control_plane.load_stack_env", return_value={"HOSTNAME_ALIAS": "live", "NEKO_INSTANCE_COUNT": "4"}):
@ -65,6 +97,59 @@ class ControlPlaneServiceTests(unittest.TestCase):
self.assertIn("neko_browser_4", links)
self.assertEqual([item["id"] for item in summary["neko_instances"]], [1, 2, 3, 4])
def test_neko_instance_status_reports_single_container_state(self) -> None:
runner = AsyncMock(return_value=(0, "running"))
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane._run_command", runner):
result = asyncio.run(neko_instance_action(2, "status"))
self.assertEqual(result["container"], "live-neko-2")
self.assertTrue(result["exists"])
self.assertTrue(result["running"])
self.assertEqual(result["status"], "running")
self.assertIn("Neko 2", result["message"])
self.assertEqual(runner.await_count, 2)
def test_neko_instance_delete_removes_container_but_preserves_profile(self) -> None:
runner = AsyncMock(
side_effect=[
(0, "running"),
(0, "live-neko-1"),
(1, "Error: No such object: live-neko-1"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane._run_command", runner):
result = asyncio.run(neko_instance_action(1, "delete"))
self.assertEqual(result["container"], "live-neko-1")
self.assertFalse(result["exists"])
self.assertFalse(result["running"])
self.assertTrue(result["profile_preserved"])
self.assertIn("配置数据已保留", result["message"])
def test_neko_instance_start_rebuilds_missing_container(self) -> None:
runner = AsyncMock(
side_effect=[
(1, "Error: No such object: live-neko-1"),
(0, "message=Neko stack started"),
(0, "running"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane.SERVICE_CTL") as service_ctl:
service_ctl.is_file.return_value = True
with patch("src.control_plane._run_command", runner):
result = asyncio.run(neko_instance_action(1, "start"))
self.assertEqual(result["container"], "live-neko-1")
self.assertTrue(result["exists"])
self.assertTrue(result["running"])
self.assertIn("重建", result["message"])
def test_network_stats_expose_realtime_and_total_bandwidth_fields(self) -> None:
stats = network_iface_stats()
for key in ("interfaces", "total_rx_bytes", "total_tx_bytes", "total_rx_bps", "total_tx_bps"):
@ -116,8 +201,38 @@ rules:
self.assertIn("ShellCrash config.yaml is missing; save/apply a YAML profile first", script)
self.assertIn('shellcrash_sync_runtime_config "$SHELLCRASH_DIR/yamls/config.yaml"', script)
self.assertIn("ShellCrash CrashCore is missing; check DNS/network and rerun apply", script)
self.assertIn("shellcrash_systemd_start()", script)
self.assertIn("systemctl start shellcrash.service", script)
self.assertIn("systemctl disable shellcrash.service", script)
self.assertIn("shellcrash_should_autostart_on_direct_fail()", script)
self.assertIn("systemctl enable --now shellcrash.service", script)
self.assertIn("SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL", script)
self.assertIn("SHELLCRASH_AUTO_START_ON_WEB_PANEL", script)
self.assertIn("shellcrash_systemd_restart", script)
self.assertIn("system_direct_global_ready()", common)
self.assertIn("shellcrash_should_autostart_on_direct_fail()", common)
self.assertIn("SHELLCRASH_AUTOSTART", common)
self.assertIn("service_homeassistant_start()", script)
self.assertIn("service_frigate_start()", script)
self.assertIn("service_frigate_auto()", script)
self.assertIn("service_wol_wake()", script)
self.assertIn("service_wol_stop()", script)
self.assertIn("service_ntfy_start()", script)
self.assertIn("service_ntfy_stop()", script)
self.assertIn("service_coturn_start()", script)
self.assertIn("coturn_secret_ready()", script)
self.assertIn("HOMEASSISTANT_AUTOSTART", common)
self.assertIn("prepare_coturn()", common)
self.assertIn("configure_host_dns()", common)
self.assertIn("configure_sudoers", common)
self.assertIn("User=root", common)
self.assertIn("Group=root", common)
self.assertNotIn("CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW", common)
self.assertIn("ensure_project_full_access()", common)
self.assertIn("prepare_homeassistant()", common)
self.assertIn("prepare_frigate()", common)
self.assertIn("prepare_ntfy()", common)
self.assertIn("install_frigate_usb_watch_service()", common)
def test_deployment_report_marks_live_local_ready_when_checks_pass(self) -> None:
with tempfile.TemporaryDirectory() as tmp:

View File

@ -0,0 +1,36 @@
from __future__ import annotations
import unittest
from src.douyin_source_display import extract_douyin_source_meta
class DouyinSourceDisplayTests(unittest.TestCase):
def test_extracts_title_from_url_line_tail(self) -> None:
meta = extract_douyin_source_meta("https://live.douyin.com/29155980665, 主播: 摆摊的小楠")
self.assertEqual(meta["source_title"], "摆摊的小楠")
self.assertEqual(meta["source_room_id"], "29155980665")
self.assertEqual(meta["source_url"], "https://live.douyin.com/29155980665")
self.assertEqual(meta["source_display"], "摆摊的小楠")
def test_extracts_title_from_recent_log(self) -> None:
meta = extract_douyin_source_meta(
"https://live.douyin.com/29155980665",
"监测 1 | 格式 YOUTUBE\n序号1 摆摊的小楠 等待直播...",
)
self.assertEqual(meta["source_title"], "摆摊的小楠")
self.assertEqual(meta["source_room_id"], "29155980665")
self.assertEqual(meta["source_display"], "摆摊的小楠")
def test_falls_back_to_room_id_when_title_is_unknown(self) -> None:
meta = extract_douyin_source_meta("https://live.douyin.com/723267141877")
self.assertEqual(meta["source_title"], "")
self.assertEqual(meta["source_room_id"], "723267141877")
self.assertEqual(meta["source_display"], "抖音直播间 723267141877")
if __name__ == "__main__":
unittest.main()

View File

@ -22,6 +22,17 @@ class HubKvStoreTests(unittest.TestCase):
self.assertEqual(rows[0]["id"], "lane1")
self.assertEqual(rows[0]["pm2Name"], "youtube2__lane1")
def test_youtube_pro_channels_clean_broken_name_before_store(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": "?? 1", "pm2Name": "youtube2__lane1"}]
)
rows = hub_kv_store.get_youtube_pro_channels()
self.assertEqual(rows[0]["name"], "线路 1")
def test_youtube_pro_channel_write_retries_after_readonly_error(self) -> None:
with patch.object(
hub_kv_store,
@ -34,6 +45,53 @@ class HubKvStoreTests(unittest.TestCase):
self.assertEqual(write.call_count, 2)
self.assertGreaterEqual(repair.call_count, 1)
def test_youtube_pro_channel_merge_preserves_existing_key_and_url(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",
"streamKey": "fresh-key",
"urlLines": "https://live.douyin.com/fresh\n",
}
]
)
rows = hub_kv_store.merge_youtube_pro_channels(
[
{
"id": "lane1",
"name": "Lane 1 stale tab",
"pm2Name": "youtube2__lane1",
"streamKey": "stale-key",
"urlLines": "https://live.douyin.com/stale\n",
}
]
)
self.assertEqual(rows[0]["name"], "Lane 1")
self.assertEqual(rows[0]["streamKey"], "fresh-key")
self.assertEqual(rows[0]["urlLines"], "https://live.douyin.com/fresh\n")
def test_youtube_pro_channel_merge_keeps_existing_rows_missing_from_stale_payload(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"},
]
)
rows = hub_kv_store.merge_youtube_pro_channels(
[{"id": "lane1", "name": "Lane 1", "pm2Name": "youtube2__lane1"}]
)
self.assertEqual([row["pm2Name"] for row in rows], ["youtube2__lane1", "youtube2__lane2"])
if __name__ == "__main__":
unittest.main()

View File

@ -4,6 +4,7 @@ import importlib.util
import os
import re
import stat
import subprocess
import sys
import unittest
from pathlib import Path
@ -20,7 +21,18 @@ class InstallBootstrapTests(unittest.TestCase):
def test_install_sh_is_remote_bootstrapper_not_thin_wrapper(self) -> None:
mode = (ROOT / "install.sh").stat().st_mode
self.assertTrue(mode & stat.S_IXUSR, "install.sh must stay executable for local installs")
executable = bool(mode & stat.S_IXUSR)
if not executable and os.name == "nt":
try:
indexed = subprocess.check_output(
["git", "ls-files", "--stage", "install.sh"],
cwd=ROOT,
text=True,
).split()
executable = bool(indexed and indexed[0] == "100755")
except (OSError, subprocess.SubprocessError):
executable = False
self.assertTrue(executable, "install.sh must stay executable for local installs")
self.assertIn("SHD2YPP2 remote bootstrapper", self.script)
self.assertIn("curl -fsSL <url>/install.sh | bash", self.script)
self.assertIn("DEFAULT_INSTALL_DIR=\"/opt/live/d2ypp\"", self.script)

View File

@ -26,6 +26,8 @@ class NekoConfigTests(unittest.TestCase):
script = script_path.read_text(encoding="utf-8")
self.assertIn("arch=\"$(uname -m", script)
self.assertIn("--disable-software-rasterizer", script)
self.assertIn("--disable-gpu-compositing", script)
self.assertIn("VizDisplayCompositor", script)
self.assertIn("--use-gl=swiftshader", script)
self.assertIn("NEKO_BROWSER_RENDER_MODE", script)
self.assertIn("NEKO_BROWSER_PROXY", script)
@ -35,6 +37,7 @@ class NekoConfigTests(unittest.TestCase):
self.assertIn(".local/share/icons/hicolor", script)
self.assertIn("--start-maximized", script)
self.assertIn("--disable-background-mode", script)
self.assertNotIn("--force-dark-mode", script)
self.assertIn("repair_profile_runtime", script)
self.assertIn('rm -rf "$target" 2>/dev/null || true', script)
self.assertIn('ensure_writable_dir "$profile_dir/Default/WebStorage/3/IndexedDB"', script)
@ -208,6 +211,7 @@ class NekoConfigTests(unittest.TestCase):
self.assertIn("chown -R \"$owner\" \"$prof\"", script)
self.assertIn("resolve_neko_browser_proxy()", script)
self.assertIn("shellcrash_mix_port()", script)
self.assertIn("shellcrash_proxy_available()", script)
self.assertIn('chmod +x "$launch"', script)
self.assertIn("copy_neko_tampermonkey_seed_dir()", script)
self.assertIn("copy_neko_tampermonkey_storage_dir()", script)
@ -258,10 +262,14 @@ class NekoConfigTests(unittest.TestCase):
self.assertIn('value.get("from_webstore") is not True', launch)
self.assertIn('path.startswith("/")', launch)
self.assertIn('value.get("location") == 8', launch)
self.assertNotIn("--load-extension=", launch)
self.assertIn("NEKO_LIVE_OPS_EXTENSION", launch)
self.assertIn("--load-extension=${live_ops_extension_dir}", launch)
self.assertNotIn("youtube-auto-dismiss-extension", launch)
self.assertIn("/etc/neko/tampermonkey-seed", launch)
self.assertIn("rm -rf \"$profile_dir/Default/Managed Extension Settings/$ext_id\"", launch)
live_ops_manifest = ROOT / "services" / "neko" / "live-ops-extension" / "manifest.json"
self.assertTrue(live_ops_manifest.is_file())
self.assertIn("Live Hub YouTube Studio Telemetry", live_ops_manifest.read_text(encoding="utf-8"))
def test_supervisor_uses_browser_launch_script(self) -> None:
chrome = (ROOT / "services" / "neko" / "google-chrome.conf").read_text(encoding="utf-8")
@ -401,19 +409,21 @@ class NekoConfigTests(unittest.TestCase):
self.assertIn("ExecStart=/bin/bash", common)
self.assertIn("scripts/linux/neko_ip_watch.sh", common)
self.assertIn("detect_preferred_lan_ip", watcher)
self.assertIn('target="$NEKO_WEBRTC_NAT1TO1"', watcher)
self.assertIn('target="$NEKO_WIREGUARD_HOST"', watcher)
self.assertIn('bash "$SERVICE_CTL" neko restart', 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"))
self.assertIn("install_neko_ip_watch_service", upgrade)
self.assertIn("live-neko-ip-watch.service", uninstall)
self.assertIn("NEKO_ACCESS_MODE=lan", stack_env)
self.assertIn("NEKO_IP_WATCH_INTERVAL=15", stack_env)
self.assertIn("NEKO_MANAGED_POLICIES=1", stack_env)
self.assertIn("NEKO_TAMPERMONKEY_REPAIR=1", stack_env)
self.assertIn("NEKO_CONTAINER_USER=neko", stack_env)
self.assertIn("NEKO_DISPLAY=:99.0", stack_env)
self.assertIn("NEKO_WIREGUARD_HOST=", stack_env)
self.assertIn("显式填入本机覆盖网络 IP 时不会被 LAN watcher 覆盖", stack_env)
self.assertIn("NEKO_ACCESS_MODE=remote", stack_env)
def test_live_console_preserves_neko_profile_ownership(self) -> None:
common = (ROOT / "scripts" / "linux" / "lib" / "common.sh").read_text(encoding="utf-8")

View File

@ -0,0 +1,118 @@
from __future__ import annotations
import os
import unittest
from unittest.mock import patch
from src import network_preflight
class NetworkPreflightTests(unittest.TestCase):
def test_direct_preflight_clears_proxy_environment(self) -> None:
def fake_probe(url: str, **kwargs):
target = "douyin" if "douyin" in url else ("youtube" if "youtube" in url else "google")
return {"ok": True, "url": url, "target": target, "elapsed_ms": 5, "status": 204}
env = {
"HTTP_PROXY": "http://127.0.0.1:7890",
"HTTPS_PROXY": "http://127.0.0.1:7890",
"ALL_PROXY": "http://127.0.0.1:7890",
"LIVE_YOUTUBE_NETWORK_MODE": "shellcrash",
}
with patch.dict(os.environ, env, clear=False):
with patch("src.network_preflight._probe_url", side_effect=fake_probe):
with patch("src.network_preflight.shellcrash_runtime", return_value={"running": False, "mixed_port": "7890"}):
result = network_preflight.youtube_network_preflight()
self.assertTrue(result["ok"])
self.assertEqual(result["mode"], "direct")
self.assertEqual(os.environ.get("LIVE_YOUTUBE_NETWORK_MODE"), "direct")
self.assertNotIn("HTTP_PROXY", os.environ)
self.assertNotIn("HTTPS_PROXY", os.environ)
self.assertNotIn("ALL_PROXY", os.environ)
def test_shellcrash_is_used_only_when_already_running(self) -> None:
def fake_probe(url: str, **kwargs):
proxy = kwargs.get("proxy")
return {"ok": bool(proxy), "url": url, "proxy": proxy or "", "elapsed_ms": 5, "status": 204 if proxy else 0}
with patch.dict(os.environ, {}, clear=False):
with patch("src.network_preflight._probe_url", side_effect=fake_probe):
with patch("src.network_preflight.shellcrash_runtime", return_value={"running": True, "mixed_port": "7890"}):
result = network_preflight.youtube_network_preflight()
self.assertTrue(result["ok"])
self.assertEqual(result["mode"], "shellcrash")
self.assertEqual(os.environ.get("LIVE_YOUTUBE_NETWORK_MODE"), "shellcrash")
self.assertIn(".douyin.com", os.environ.get("NO_PROXY", ""))
def test_failed_preflight_keeps_shellcrash_manual(self) -> None:
def fake_probe(url: str, **kwargs):
return {"ok": False, "url": url, "elapsed_ms": 5, "error": "blocked"}
with patch.dict(os.environ, {"HTTP_PROXY": "http://127.0.0.1:7890"}, clear=False):
with patch("src.network_preflight._probe_url", side_effect=fake_probe):
with patch("src.network_preflight.shellcrash_runtime", return_value={"running": False, "mixed_port": "7890"}):
with patch("src.network_preflight.shellcrash_config_status", return_value={"available": False, "path": "", "bytes": 0}):
result = network_preflight.youtube_network_preflight()
self.assertFalse(result["ok"])
self.assertEqual(result["mode"], "failed")
self.assertIn("ShellCrash is not running", result["message"])
self.assertEqual(os.environ.get("LIVE_YOUTUBE_NETWORK_MODE"), "failed")
self.assertNotIn("HTTP_PROXY", os.environ)
def test_direct_failure_autostarts_shellcrash_when_config_exists(self) -> None:
runtime_states = [
{"running": False, "mixed_port": "7890"},
{"running": True, "mixed_port": "7890"},
{"running": True, "mixed_port": "7890"},
]
def fake_runtime():
return runtime_states.pop(0) if runtime_states else {"running": True, "mixed_port": "7890"}
def fake_probe(url: str, **kwargs):
proxy = kwargs.get("proxy")
return {"ok": bool(proxy), "url": url, "proxy": proxy or "", "elapsed_ms": 5, "status": 204 if proxy else 0}
commands: list[list[str]] = []
def fake_run(args: list[str], **kwargs):
commands.append(args)
if args[:2] == ["systemctl", "list-unit-files"]:
return 0, "shellcrash.service enabled"
return 0, "ok"
with patch.dict(os.environ, {}, clear=False):
with patch("src.network_preflight._probe_url", side_effect=fake_probe):
with patch("src.network_preflight.shellcrash_runtime", side_effect=fake_runtime):
with patch("src.network_preflight.shellcrash_config_status", return_value={"available": True, "path": "/etc/ShellCrash/yamls/config.yaml", "bytes": 12}):
with patch("src.network_preflight._stage_shellcrash_runtime_config"):
with patch("src.network_preflight._run", side_effect=fake_run):
with patch("src.network_preflight.time.sleep"):
result = network_preflight.youtube_network_preflight()
self.assertTrue(result["ok"])
self.assertEqual(result["mode"], "shellcrash")
self.assertTrue(result["shellcrash_autostart"]["attempted"])
self.assertIn(["systemctl", "enable", "--now", "shellcrash.service"], commands)
def test_system_probe_reports_google_and_douyin(self) -> None:
def fake_probe(url: str, **kwargs):
return {"ok": True, "url": url, "elapsed_ms": 7, "status": 200}
with patch("src.network_preflight._probe_url", side_effect=fake_probe):
with patch("src.network_preflight.shellcrash_runtime", return_value={"running": False, "mixed_port": "7890"}):
result = network_preflight.system_network_probe()
targets = {item["target"] for item in result["direct"]}
self.assertIn("google", targets)
self.assertIn("youtube", targets)
self.assertIn("douyin", targets)
self.assertEqual(result["mode"], "direct")
self.assertEqual(result["shellcrash_policy"]["recommendation"], "keep_shellcrash_stopped")
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,61 @@
from __future__ import annotations
import tempfile
import unittest
import zipfile
from pathlib import Path
from unittest.mock import patch
from src.ops_center import app_blueprints, create_system_snapshot, studio_ops_summary, system_doctor
class OpsCenterTests(unittest.TestCase):
def test_system_doctor_scores_critical_service_failures(self) -> None:
services = [
{"service_id": "srs", "available": True, "running": False, "detail": "stopped"},
{"service_id": "neko", "available": True, "running": True, "detail": "running"},
{"service_id": "wol", "available": True, "running": False, "detail": "ready"},
]
doctor = system_doctor(services, {"ready": True, "pass_count": 3, "total_count": 3})
self.assertEqual(doctor["critical"], 1)
self.assertLess(doctor["score"], 100)
self.assertIn("srs", "\n".join(doctor["recommendations"]))
def test_app_blueprints_mark_installed_services(self) -> None:
rows = app_blueprints({"homeassistant", "coturn"})
by_id = {item["id"]: item for item in rows}
self.assertTrue(by_id["homeassistant"]["installed"])
self.assertTrue(by_id["coturn"]["installed"])
self.assertFalse(by_id["freshrss"]["installed"])
def test_create_system_snapshot_includes_managed_configs(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
(base / "config").mkdir()
(base / "config" / "system-stack.env").write_text("PORT=8001\n", encoding="utf-8")
(base / "services" / "ntfy" / "config").mkdir(parents=True)
(base / "services" / "ntfy" / "config" / "server.yml").write_text("base-url: http://live.local:8089\n", encoding="utf-8")
result = create_system_snapshot(base, reason="unit test")
snapshot_path = Path(result["snapshot"]["path"])
with zipfile.ZipFile(snapshot_path) as archive:
names = set(archive.namelist())
self.assertIn("manifest.json", names)
self.assertIn("config/system-stack.env", names)
self.assertIn("services/ntfy/config/server.yml", names)
self.assertGreater(result["snapshot"]["included"], 0)
def test_studio_ops_summary_combines_doctor_inventory_and_recipes(self) -> None:
services = [{"service_id": "wol", "available": True, "running": False, "detail": "ready"}]
with tempfile.TemporaryDirectory() as tmp:
with patch("src.ops_center.list_serial_ports", return_value=[{"path": "/dev/ttyUSB0"}]):
with patch("src.ops_center.list_video_devices", return_value=[{"path": "/dev/video0"}]):
summary = studio_ops_summary(services, {"ready": False, "pass_count": 1, "total_count": 2}, Path(tmp))
self.assertIn("doctor", summary)
self.assertEqual(summary["inventory"]["counts"]["serial"], 1)
self.assertEqual(summary["inventory"]["counts"]["video"], 1)
self.assertTrue(summary["recipes"])
if __name__ == "__main__":
unittest.main()

View File

@ -40,6 +40,19 @@ class ProcessRuntimeStatusTests(unittest.TestCase):
self.assertEqual(state["business_status"], "waiting_source")
self.assertFalse(state["is_pushing"])
def test_summarize_process_activity_marks_no_record_task_as_waiting_source(self) -> None:
state = summarize_process_activity(
"youtube2__lane1",
"online",
"监测 1 | 格式 YOUTUBE | 错误 0\n无录制任务 | 循环间隔 120s",
"",
log_age_seconds=4.0,
ffmpeg_pids=[],
)
self.assertEqual(state["business_status"], "waiting_source")
self.assertFalse(state["is_pushing"])
def test_summarize_process_activity_marks_misconfigured(self) -> None:
state = summarize_process_activity(
"youtube",
@ -51,6 +64,54 @@ class ProcessRuntimeStatusTests(unittest.TestCase):
)
self.assertEqual(state["business_status"], "misconfigured")
def test_summarize_process_activity_marks_youtube_key_rejected(self) -> None:
state = summarize_process_activity(
"youtube",
"online",
"",
"\n".join(
(
"[FFmpeg] [tls @ 0x1] Error in the pull function.",
"[FFmpeg] [tls @ 0x1] IO error: End of file",
"[FFmpeg] Error opening output file rtmps://a.rtmps.youtube.com/live2/bad-key.",
"[FFmpeg] Error opening output files: Input/output error",
)
),
log_age_seconds=2.0,
ffmpeg_pids=[],
)
self.assertEqual(state["business_status"], "youtube_key_rejected")
self.assertFalse(state["is_pushing"])
def test_summarize_process_activity_keeps_streaming_when_ffmpeg_is_active_with_old_key_error(self) -> None:
state = summarize_process_activity(
"youtube",
"online",
"",
"\n".join(
(
"[FFmpeg] Error opening output file rtmps://a.rtmps.youtube.com/live2/old-bad-key.",
"[FFmpeg] Error opening output files: Input/output error",
)
),
log_age_seconds=2.0,
ffmpeg_pids=[4321],
)
self.assertEqual(state["business_status"], "streaming")
self.assertTrue(state["is_pushing"])
def test_summarize_process_activity_marks_streaming_from_recent_ffmpeg_progress(self) -> None:
state = summarize_process_activity(
"youtube",
"online",
"[FFmpeg] frame=27022 fps=30 time=00:15:00.70 bitrate=4108.0kbits/s speed=0.995x",
"",
log_age_seconds=0.4,
ffmpeg_pids=[],
)
self.assertEqual(state["business_status"], "streaming")
self.assertTrue(state["is_pushing"])
def test_summarize_process_activity_marks_stale_when_heartbeat_is_old(self) -> None:
state = summarize_process_activity(
"youtube",

View File

@ -0,0 +1,135 @@
from __future__ import annotations
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import Mock, patch
from src import studio_control
from src.studio_control import (
delete_wol_device,
list_wol_devices,
normalize_mac_address,
probe_wol_devices,
send_serial_command,
send_wake_on_lan,
upsert_wol_device,
)
class StudioControlTests(unittest.TestCase):
def test_normalize_mac_accepts_common_formats(self) -> None:
self.assertEqual(normalize_mac_address("aa:bb:cc:dd:ee:ff"), "AA:BB:CC:DD:EE:FF")
self.assertEqual(normalize_mac_address("aa-bb-cc-dd-ee-ff"), "AA:BB:CC:DD:EE:FF")
self.assertEqual(normalize_mac_address("aabb.ccdd.eeff"), "AA:BB:CC:DD:EE:FF")
def test_wol_sends_magic_packet_to_broadcast(self) -> None:
sock = Mock()
sock.sendto.return_value = 102
with patch("src.studio_control.socket.socket", return_value=sock):
result = send_wake_on_lan("AA:BB:CC:DD:EE:FF", "192.168.1.255", 9)
payload, target = sock.sendto.call_args.args
self.assertEqual(target, ("192.168.1.255", 9))
self.assertEqual(payload[:6], bytes.fromhex("FF" * 6))
self.assertEqual(payload[6:12], bytes.fromhex("AABBCCDDEEFF"))
self.assertEqual(len(payload), 102)
self.assertEqual(result["bytes"], 102)
self.assertEqual(result["mac"], "AA:BB:CC:DD:EE:FF")
def test_wol_rejects_invalid_inputs(self) -> None:
with self.assertRaises(ValueError):
send_wake_on_lan("not-a-mac")
with self.assertRaises(ValueError):
send_wake_on_lan("AA:BB:CC:DD:EE:FF", "not-an-ip")
with self.assertRaises(ValueError):
send_wake_on_lan("AA:BB:CC:DD:EE:FF", port=70000)
def test_wol_device_store_supports_manual_edit_and_delete(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
base_dir = Path(tmp)
saved = upsert_wol_device("NAS", "aa-bb-cc-dd-ee-ff", "192.168.1.20", base_dir)
devices = list_wol_devices(base_dir)
deleted = delete_wol_device("AA:BB:CC:DD:EE:FF", base_dir)
self.assertEqual(saved["mac"], "AA:BB:CC:DD:EE:FF")
self.assertEqual(saved["source"], "manual")
self.assertEqual(saved["ip"], "192.168.1.20")
self.assertEqual(devices[0]["name"], "NAS")
self.assertEqual(deleted["devices"], [])
def test_wol_probe_merges_neighbor_cache_and_manual_devices(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
base_dir = Path(tmp)
upsert_wol_device("Studio PC", "AA:BB:CC:DD:EE:FF", "192.168.1.20", base_dir)
neighbor = {
"id": "11:22:33:44:55:66",
"name": "192.168.1.21",
"mac": "11:22:33:44:55:66",
"ip": "192.168.1.21",
"reachable": True,
"source": "neigh",
"last_seen": 1000.0,
"updated_at": 1000.0,
}
with patch("src.studio_control._ping_host", return_value=True):
with patch("src.studio_control._ip_neigh_devices", return_value=[neighbor]):
with patch("src.studio_control.time.time", return_value=1000.0):
result = probe_wol_devices(base_dir)
by_mac = {item["mac"]: item for item in result["devices"]}
self.assertEqual(result["count"], 2)
self.assertTrue(by_mac["AA:BB:CC:DD:EE:FF"]["reachable"])
self.assertEqual(by_mac["AA:BB:CC:DD:EE:FF"]["name"], "Studio PC")
self.assertEqual(by_mac["11:22:33:44:55:66"]["source"], "neigh")
def test_wol_probe_filters_virtual_interfaces_and_stale_auto_devices(self) -> None:
raw_neigh = "\n".join(
[
"10.0.0.1 dev eno1 lladdr d2:54:cd:ab:fe:73 REACHABLE",
"172.18.0.2 dev br-123456 lladdr 62:ca:f6:01:39:7f STALE",
]
)
with patch("src.studio_control._run_text", return_value=raw_neigh):
with patch.dict(studio_control.os.environ, {"WOL_PROBE_CIDR": ""}, clear=False):
devices = studio_control._ip_neigh_devices()
self.assertEqual([item["mac"] for item in devices], ["D2:54:CD:AB:FE:73"])
with tempfile.TemporaryDirectory() as tmp:
base_dir = Path(tmp)
store = base_dir / "config" / "wol_devices.json"
store.parent.mkdir(parents=True)
store.write_text(
json.dumps(
[
{
"id": "62:CA:F6:01:39:7F",
"name": "172.18.0.2",
"mac": "62:CA:F6:01:39:7F",
"ip": "172.18.0.2",
"source": "neigh",
}
]
),
encoding="utf-8",
)
with patch("src.studio_control._ping_host", return_value=False):
with patch("src.studio_control._ip_neigh_devices", return_value=devices):
result = probe_wol_devices(base_dir)
self.assertEqual([item["mac"] for item in result["devices"]], ["D2:54:CD:AB:FE:73"])
def test_wol_device_rejects_invalid_ip(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
with self.assertRaises(ValueError):
upsert_wol_device("Bad", "AA:BB:CC:DD:EE:FF", "not-an-ip", Path(tmp))
def test_serial_command_rejects_unsupported_port_path(self) -> None:
with patch.object(studio_control, "termios", object()):
with self.assertRaises(ValueError):
send_serial_command("/tmp/not-serial", "AT")
if __name__ == "__main__":
unittest.main()

View File

@ -5,6 +5,7 @@ from unittest.mock import patch
from src.wireguard_config import (
WireGuardConfigError,
configure_neko_wireguard_access,
normalize_wireguard_overlay_config,
parse_wireguard_config,
save_imported_wireguard_config,
@ -176,7 +177,7 @@ class WireGuardConfigTests(unittest.TestCase):
self.assertEqual(status["quality"]["configured_peer_count"], 1)
self.assertIn("start wg-quick@wg-vps", " ".join(status["recommendations"]))
def test_runtime_status_reports_quality_and_neko_remote_urls(self) -> None:
def test_runtime_status_reports_quality_and_configured_neko_remote_urls(self) -> None:
now = 1_700_000_000
def fake_run(args: list[str], **_: object) -> dict[str, object]:
@ -207,7 +208,7 @@ class WireGuardConfigTests(unittest.TestCase):
env = Path(tmp) / "config" / "system-stack.env"
env.parent.mkdir(parents=True)
env.write_text(
"NEKO_WIREGUARD_HOST=10.88.0.2\nNEKO_INSTANCE_COUNT=2\nNEKO_HTTP_PORT=9200\n",
"NEKO_ACCESS_MODE=remote\nNEKO_WIREGUARD_HOST=10.88.0.2\nNEKO_INSTANCE_COUNT=2\nNEKO_HTTP_PORT=9200\n",
encoding="utf-8",
)
with patch("src.wireguard_config.shutil.which", return_value="/usr/bin/tool"), patch(
@ -219,8 +220,16 @@ class WireGuardConfigTests(unittest.TestCase):
self.assertEqual(status["quality"]["status"], "connected")
self.assertEqual(status["quality"]["fresh_peer_count"], 1)
self.assertEqual(status["quality"]["best_handshake_age_seconds"], 30)
self.assertEqual(status["neko"]["remote_urls"][0]["url"], "http://10.88.0.2:9200")
self.assertEqual(status["neko"]["remote_urls"][1]["url"], "http://10.88.0.2:9201")
self.assertEqual(status["neko_access"]["mode"], "remote")
self.assertTrue(status["neko_access"]["remote_ready"])
self.assertEqual(status["neko_access"]["remote_urls"][0]["url"], "http://10.88.0.2:9200")
self.assertEqual(status["neko_access"]["remote_urls"][1]["url"], "http://10.88.0.2:9201")
def test_configure_neko_remote_requires_active_wireguard(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
with patch("src.wireguard_config.wireguard_runtime_status", return_value={"active": False, "interfaces": []}):
with self.assertRaises(WireGuardConfigError):
configure_neko_wireguard_access(repo_root=Path(tmp), mode="remote", restart=False)
if __name__ == "__main__":

View File

@ -0,0 +1,108 @@
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from src.youtube_live_store import (
close_live_event,
get_live_event,
ingest_browser_telemetry,
list_live_events,
record_control_action,
record_process_observation,
youtube_live_summary,
)
class YoutubeLiveStoreTests(unittest.TestCase):
def test_control_action_creates_traceable_event(self) -> None:
with tempfile.TemporaryDirectory() as td:
db = Path(td) / "hub_state.sqlite"
result = record_control_action(
"youtube",
"start",
script="youtube.py",
url_lines="https://live.douyin.com/12345678\n",
youtube_ini_text="[youtube]\nkey = abcd-efgh-ijkl\n",
db_path=db,
)
event = result["event"]
self.assertEqual(event["process"], "youtube")
self.assertEqual(event["source_room_id"], "12345678")
self.assertEqual(event["youtube_key_suffix"], "h-ijkl")
self.assertEqual(event["status"], "active")
closed = close_live_event(event["id"], db_path=db)
self.assertEqual(closed["event"]["status"], "ended")
self.assertIsNotNone(closed["event"]["ended_at"])
def test_browser_telemetry_adds_samples_and_alerts(self) -> None:
with tempfile.TemporaryDirectory() as td:
db = Path(td) / "hub_state.sqlite"
result = ingest_browser_telemetry(
{
"process": "youtube2__lane1",
"url": "https://studio.youtube.com/video/abc/livestreaming",
"page_title": "Live Control Room",
"stream_title": "Relay: Douyin room",
"source_url": "https://live.douyin.com/9988",
"live_status": "live",
"health": "excellent",
"viewer_count": 42,
"popups": ["Stream is healthy"],
},
db_path=db,
)
event = result["event"]
self.assertEqual(event["source_room_id"], "9988")
self.assertEqual(event["last_viewer_count"], 42)
self.assertGreaterEqual(event["quality_score"], 80)
detail = get_live_event(event["id"], db_path=db)
self.assertEqual(detail["sample_count"], 1)
self.assertEqual(len(detail["samples"]), 1)
self.assertEqual(len(detail["alerts"]), 1)
listing = list_live_events(limit=10, db_path=db)
self.assertEqual(listing["total"], 1)
summary = youtube_live_summary(db_path=db)
self.assertEqual(summary["stats"]["active_events"], 1)
self.assertIn("browser_extension_telemetry", summary["capabilities"])
def test_inactive_process_observation_closes_active_event(self) -> None:
with tempfile.TemporaryDirectory() as td:
db = Path(td) / "hub_state.sqlite"
created = record_control_action(
"youtube",
"restart",
url_lines="https://live.douyin.com/456789\n",
youtube_ini_text="[youtube]\nkey = test-key-456789\n",
db_path=db,
)
self.assertEqual(created["event"]["status"], "active")
result = record_process_observation(
"youtube",
{
"raw_status": "Process is configured but not running",
"process_status": "configured",
"business_status": "ready",
"business_note": "Process is configured but not running",
"ffmpeg_active": False,
"is_pushing": False,
},
url_lines="https://live.douyin.com/456789\n",
db_path=db,
)
self.assertEqual(result["count"], 1)
summary = youtube_live_summary(db_path=db)
self.assertEqual(summary["stats"]["active_events"], 0)
detail = get_live_event(created["event"]["id"], db_path=db)
self.assertEqual(detail["status"], "ended")
self.assertIsNotNone(detail["ended_at"])
if __name__ == "__main__":
unittest.main()

View File

@ -30,6 +30,19 @@ class YoutubeProRuntimeTests(unittest.TestCase):
]
)
def test_normalize_channels_cleans_broken_lane_names(self) -> None:
rows = normalize_youtube_pro_channels(
[
{"id": "lane1", "name": "?? 1", "pm2Name": "youtube2__lane1"},
{"id": "lane2", "name": "绾胯矾 2", "pm2Name": "youtube2__lane2"},
{"id": "lane3", "name": "正常线路", "pm2Name": "youtube2__lane3"},
]
)
self.assertEqual(rows[0]["name"], "线路 1")
self.assertEqual(rows[1]["name"], "线路 2")
self.assertEqual(rows[2]["name"], "正常线路")
def test_materialize_runtime_files_from_saved_channel_payload(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
config_dir = Path(tmp)

View File

@ -0,0 +1,72 @@
from __future__ import annotations
import unittest
from src.youtube_quality_guard import build_youtube_quality_guard_report, parse_ffmpeg_metrics
class YoutubeQualityGuardTests(unittest.TestCase):
def test_parse_ffmpeg_metrics_from_stats_line(self) -> None:
metrics = parse_ffmpeg_metrics(
"frame= 1200 fps=30.0 bitrate=4500.5kbits/s speed=1.02x dup=0 drop=1 time=00:00:40.00"
)
self.assertEqual(metrics["frame"], 1200)
self.assertEqual(metrics["fps"], 30.0)
self.assertEqual(metrics["bitrate"], 4500.5)
self.assertEqual(metrics["speed"], 1.02)
self.assertEqual(metrics["drop"], 1)
self.assertEqual(metrics["encoded_time"], "00:00:40.00")
def test_quality_report_flags_inactive_lane_and_missing_studio_samples(self) -> None:
report = build_youtube_quality_guard_report(
[
{
"pm2": "youtube",
"label": "YouTube",
"process_status": "configured",
"business_status": "ready",
"ffmpeg_active": False,
"is_pushing": False,
"recent_log": "Process is configured but not running",
"recent_error": "",
}
],
live_summary={"stats": {"active_events": 0, "sample_count": 0, "viewer_peak": 0}},
config_by_process={"youtube": {"youtube_ini_text": "[youtube]\nkey = demo\nrtmps = 是\n", "url_lines": "https://live.douyin.com/123\n"}},
)
self.assertEqual(report["summary"]["lanes"], 1)
self.assertEqual(report["summary"]["pushing_lanes"], 0)
self.assertLess(report["score"], 60)
self.assertIn("没有正在推流", report["recommendations"][0]["text"])
self.assertIn("FFmpeg 未检测到", report["lanes"][0]["issues"][0]["text"])
self.assertEqual(report["lanes"][0]["source_display"], "抖音直播间 123")
def test_quality_report_passes_human_source_display(self) -> None:
report = build_youtube_quality_guard_report(
[
{
"pm2": "youtube2__ch_demo",
"label": "线路 1",
"process_status": "online",
"business_status": "waiting_source",
"ffmpeg_active": False,
"is_pushing": False,
"recent_log": "序号1 小郑的摆摊日记 等待直播...",
"recent_error": "",
}
],
config_by_process={
"youtube2__ch_demo": {
"youtube_ini_text": "[youtube]\nkey = demo\nrtmps = 是\n",
"url_lines": "https://live.douyin.com/543245436004\n",
}
},
)
self.assertEqual(report["lanes"][0]["source_title"], "小郑的摆摊日记")
self.assertEqual(report["lanes"][0]["source_room_id"], "543245436004")
self.assertEqual(report["lanes"][0]["source_display"], "小郑的摆摊日记")
if __name__ == "__main__":
unittest.main()

View File

@ -60,12 +60,14 @@ def _discover_repo_files() -> list[str]:
"services/*/docker-compose.yml",
"services/*/docker-compose.yaml",
"services/neko/external-extensions/**/*",
"services/neko/live-ops-extension/**/*",
"services/neko/policies/**/*",
"services/neko/provisioning/**/*",
"services/neko/tampermonkey-seed/**/*",
"services/neko/*.conf",
"services/**/*.sh",
"src/**/*.py",
"tests/**/*.py",
"tiktok/**/*.sh",
"tools/*.py",
"web-console/*.json",
@ -402,7 +404,8 @@ def main() -> int:
client,
log_path,
"chmod_uploaded_runtime_scripts",
f"chmod +x {REMOTE_BASE}/scripts/linux/service_ctl.sh "
f"chmod +x {REMOTE_BASE}/install.sh "
f"{REMOTE_BASE}/scripts/linux/service_ctl.sh "
f"{REMOTE_BASE}/scripts/linux/refresh_live_console_unit.sh "
f"{REMOTE_BASE}/scripts/linux/reinstall_live_edge.sh "
f"{REMOTE_BASE}/services/neko/browser-launch.sh 2>/dev/null || true; echo chmod_ok",
@ -416,6 +419,42 @@ def main() -> int:
timeout=180,
stdin_text=f"{PASS}\n",
)
prepare_python_runtime = (
"sudo -S -p '' bash -lc '"
f"cd {REMOTE_BASE}; "
". scripts/linux/lib/common.sh; "
"ensure_live_user; "
"ensure_live_can_traverse_repo_root; "
"prepare_python_runtime'"
)
code_runtime, _ = run_logged(
client,
log_path,
"prepare_python_runtime",
prepare_python_runtime,
timeout=900,
stdin_text=f"{PASS}\n",
)
if code_runtime != 0:
_safe_print("Remote Python runtime preparation failed; see deploy log")
return 3
verify_python_runtime = (
f"cd {REMOTE_BASE} && .venv/bin/python - <<'PY'\n"
"for name in ('loguru', 'distro', 'fastapi', 'uvicorn'):\n"
" __import__(name)\n"
"print('python_runtime_ok')\n"
"PY"
)
code_runtime_verify, _ = run_logged(
client,
log_path,
"verify_python_runtime",
verify_python_runtime,
timeout=90,
)
if code_runtime_verify != 0:
_safe_print("Remote Python runtime import check failed; see deploy log")
return 3
run_logged(
client,
log_path,
@ -431,15 +470,42 @@ def main() -> int:
timeout=15,
)
syntax_files = [
"web.py",
"youtube.py",
"tiktok.py",
"ffmpeg_install.py",
"backup/__init__.py",
"backup/msg_push.py",
"backup/robust_relay.py",
"src/utils.py",
"src/logger.py",
"src/spider.py",
"src/stream.py",
"src/proxy.py",
"src/http_clients/async_http.py",
"src/http_clients/sync_http.py",
"src/control_plane.py",
"src/web_process_backend.py",
"src/hub_routes.py",
"src/hub_kv_store.py",
"src/async_thread_loop.py",
"src/youtube_ini_sync.py",
"src/live_config/__init__.py",
"src/live_config/loader.py",
"scripts/hardware_probe.py",
"douyin_youtube_ffplay.py",
"main.py",
]
py_compile = (
f"cd {REMOTE_BASE} && python3 -m py_compile web.py youtube.py tiktok.py ffmpeg_install.py "
"backup/__init__.py backup/msg_push.py backup/robust_relay.py "
"src/utils.py src/logger.py src/spider.py src/stream.py src/proxy.py "
"src/http_clients/async_http.py src/http_clients/sync_http.py "
"src/control_plane.py src/web_process_backend.py src/hub_routes.py src/hub_kv_store.py "
"src/async_thread_loop.py src/youtube_ini_sync.py "
"src/live_config/__init__.py src/live_config/loader.py "
"scripts/hardware_probe.py douyin_youtube_ffplay.py main.py"
f"cd {REMOTE_BASE} && python3 - <<'PY'\n"
"from pathlib import Path\n"
f"files = {syntax_files!r}\n"
"for rel in files:\n"
" text = Path(rel).read_text(encoding='utf-8', errors='replace')\n"
" compile(text, rel, 'exec')\n"
"print('syntax_ok')\n"
"PY"
)
code_py, _ = run_logged(client, log_path, "python_py_compile", py_compile, timeout=90)
if code_py != 0:
@ -452,18 +518,28 @@ def main() -> int:
"未完成前日志不会出现 exit=,属正常现象。\n",
)
_safe_print("远端正在构建 web-console(请耐心等待,ARM 可能较久)…")
remote_web_console = f"{REMOTE_BASE}/web-console"
build_cmd = (
f"cd {REMOTE_BASE}/web-console && "
"sudo -S -p '' bash -lc '"
f"cd {remote_web_console} && "
"if [ -f out/index.html ] && [ ! -x node_modules/.bin/next ]; then "
"echo using_prebuilt_web_console_out; "
"elif [ -x node_modules/.bin/next ]; then "
"npm run build; "
f"runuser -u live -- bash -lc \"cd {remote_web_console} && npm run build\"; "
"else "
f"runuser -u live -- bash -lc \"cd {remote_web_console} && "
"(npm ci --prefer-offline --no-audit --fund=false 2>/dev/null || "
"npm install --prefer-offline --no-audit --fund=false) && npm run build; "
"fi"
"npm install --prefer-offline --no-audit --fund=false) && npm run build\"; "
"fi'"
)
code_b, _ = run_logged(
client,
log_path,
"web_console_build",
build_cmd,
timeout=2400,
stdin_text=f"{PASS}\n",
)
code_b, _ = run_logged(client, log_path, "web_console_build", build_cmd, timeout=2400)
if code_b != 0:
_safe_print("[警告] web-console build 非 0(可能未装 Node/pnpm),完整输出见日志")
@ -524,12 +600,12 @@ def main() -> int:
client,
log_path,
"curl_health_after_restart",
"for i in $(seq 1 22); do "
"for i in $(seq 1 60); do "
"if curl -sf -m 4 http://127.0.0.1:8001/health >/dev/null 2>&1; then echo \"health_ok_8001\"; exit 0; fi; "
"if curl -sf -m 4 http://127.0.0.1:8101/health >/dev/null 2>&1; then echo \"health_ok_8101\"; exit 0; fi; "
"sleep 2; "
"done; echo curl_health_failed; exit 0",
timeout=120,
timeout=180,
)
# 若健康检查失败,再尝试 reset-failed + start(部分板子 restart 后 unit 未 active)
recover_console = (
@ -545,10 +621,10 @@ def main() -> int:
client,
log_path,
"curl_health_after_recover",
"for i in $(seq 1 12); do "
"for i in $(seq 1 60); do "
"if curl -sf -m 4 http://127.0.0.1:8001/health >/dev/null 2>&1; then echo health_ok_recover; exit 0; fi; "
"sleep 2; done; echo still_failed; exit 0",
timeout=60,
timeout=180,
)
run_logged(
client,

View File

@ -64,6 +64,7 @@ def render(count: int) -> str:
)
supervisor_conf = env("NEKO_BROWSER_SUPERVISOR_CONF", "chromium.conf")
tampermonkey_repair = env("NEKO_TAMPERMONKEY_REPAIR", "1")
live_ops_extension = env("NEKO_LIVE_OPS_EXTENSION", "1")
base_profile = env("NEKO_PROFILE_HOST_DIR", str(Path.cwd() / "data" / "chromium-profile-v2"))
http_base = int(env("NEKO_HTTP_PORT", "9200"))
mux_base = int(env("NEKO_WEBRTC_TCPMUX", "52300"))
@ -118,6 +119,8 @@ def render(count: int) -> str:
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)}",
f" NEKO_LIVE_OPS_EXTENSION: {q(live_ops_extension)}",
' NEKO_LIVE_OPS_EXTENSION_DIR: "/etc/neko/live-ops-extension"',
f" NEKO_WEBRTC_EPR: {q(epr)}",
f" NEKO_WEBRTC_TCPMUX: {q(tcp_mux)}",
f" NEKO_WEBRTC_UDPMUX: {q(udp_mux)}",
@ -133,6 +136,7 @@ def render(count: int) -> str:
f" - {q(f'{policy_dir}:/etc/chromium-browser/policies/managed:ro')}",
f" - {q(f'{policy_dir}:/etc/opt/chrome/policies/managed:ro')}",
' - "./tampermonkey-seed:/etc/neko/tampermonkey-seed:ro"',
' - "./live-ops-extension:/etc/neko/live-ops-extension:ro"',
' - "./provisioning:/var/www/provisioning:ro"',
' - "./browser-launch.sh:/etc/neko/browser-launch.sh:ro"',
f" - {q(f'./{supervisor_conf}:/etc/neko/supervisord/{supervisor_conf}:ro')}",

View File

@ -0,0 +1,3 @@
"use client";
export { default } from "@/components/live-product/LiveControlApp";

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,10 @@
"use client";
import { ExternalLink, Pause, Play, RefreshCw } from "lucide-react";
import { AlertTriangle, ExternalLink, Pause, Play, RefreshCw } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import {
douyinSourceDisplayFrom,
extractDouyinCurrentRoomFromLog,
extractDouyinLiveUrls,
extractDouyinRoomHints,
@ -20,6 +21,10 @@ type StatusPayload = {
ffmpeg_pids?: number[];
log_age_seconds?: number | null;
is_pushing?: boolean;
source_title?: string;
source_room_id?: string;
source_url?: string;
source_display?: string;
};
function fmtDuration(sec: number): string {
@ -62,6 +67,11 @@ function businessLine(t: TFn, raw: string | undefined, note: string | undefined)
return t("Source live detected, but no active FFmpeg relay worker", "Source live detected, but no active FFmpeg relay worker");
if (s === "monitoring") return t("Process online and monitoring the source", "Process online and monitoring the source");
if (s === "misconfigured") return t("YouTube key missing or invalid", "YouTube key missing or invalid");
if (s === "youtube_key_rejected")
return t(
"YouTube 推流失败:串流密钥无效、过期或不属于当前直播间",
"YouTube rejected the stream key",
);
if (s === "stale") return t("Process online but the log heartbeat is stale", "Process online but the log heartbeat is stale");
if (s === "error") return t("Recent process error detected", "Recent process error detected");
if (note?.trim()) return note.trim();
@ -85,6 +95,10 @@ export function LiveProcessLiveLogCard({
const [businessNote, setBusinessNote] = useState("");
const [ffmpegPids, setFfmpegPids] = useState<number[]>([]);
const [logAgeSeconds, setLogAgeSeconds] = useState<number | null>(null);
const [sourceTitle, setSourceTitle] = useState("");
const [sourceRoomId, setSourceRoomId] = useState("");
const [sourceUrl, setSourceUrl] = useState("");
const [sourceDisplay, setSourceDisplay] = useState("");
const [paused, setPaused] = useState(false);
const [liveSince, setLiveSince] = useState<number | null>(null);
const [nowTick, setNowTick] = useState(0);
@ -101,8 +115,14 @@ export function LiveProcessLiveLogCard({
const onlineNow = /^(online|running)$/i.test(processStatus);
const roomFromLog = extractDouyinCurrentRoomFromLog(recentLog);
const fallbackUrl = extractDouyinLiveUrls(urlListText)[0] ?? "";
const primaryRoomId = roomFromLog || (fallbackUrl.match(/live\.douyin\.com\/([a-zA-Z0-9_-]+)/i)?.[1] ?? null);
const primaryUrl = primaryRoomId ? `https://live.douyin.com/${primaryRoomId}` : fallbackUrl || null;
const primaryRoomId = sourceRoomId || roomFromLog || (fallbackUrl.match(/live\.douyin\.com\/([a-zA-Z0-9_-]+)/i)?.[1] ?? null);
const primaryUrl = sourceUrl || (primaryRoomId ? `https://live.douyin.com/${primaryRoomId}` : fallbackUrl || null);
const primarySourceLabel =
sourceDisplay ||
sourceTitle ||
douyinSourceDisplayFrom(urlListText, recentLog) ||
(primaryRoomId ? `抖音直播间 ${primaryRoomId}` : "");
const youtubeKeyRejected = businessStatus.trim().toLowerCase() === "youtube_key_rejected";
const pull = useCallback(async () => {
const targetProc = currentProcRef.current.trim();
@ -126,6 +146,10 @@ export function LiveProcessLiveLogCard({
setBusinessNote(data.business_note || "");
setFfmpegPids(Array.isArray(data.ffmpeg_pids) ? data.ffmpeg_pids : []);
setLogAgeSeconds(typeof data.log_age_seconds === "number" ? data.log_age_seconds : null);
setSourceTitle(data.source_title || "");
setSourceRoomId(data.source_room_id || "");
setSourceUrl(data.source_url || "");
setSourceDisplay(data.source_display || "");
const online = /^(online|running)$/i.test(ps);
if (online && !prevOnlineRef.current) {
setLiveSince(Date.now());
@ -141,6 +165,10 @@ export function LiveProcessLiveLogCard({
setBusinessNote("");
setFfmpegPids([]);
setLogAgeSeconds(null);
setSourceTitle("");
setSourceRoomId("");
setSourceUrl("");
setSourceDisplay("");
} finally {
pullInFlightRef.current = false;
if (pullQueuedRef.current) {
@ -162,6 +190,10 @@ export function LiveProcessLiveLogCard({
setBusinessNote("");
setFfmpegPids([]);
setLogAgeSeconds(null);
setSourceTitle("");
setSourceRoomId("");
setSourceUrl("");
setSourceDisplay("");
setLiveSince(null);
prevOnlineRef.current = false;
return;
@ -173,6 +205,10 @@ export function LiveProcessLiveLogCard({
setBusinessNote("");
setFfmpegPids([]);
setLogAgeSeconds(null);
setSourceTitle("");
setSourceRoomId("");
setSourceUrl("");
setSourceDisplay("");
setLiveSince(null);
prevOnlineRef.current = false;
void pull();
@ -304,6 +340,19 @@ export function LiveProcessLiveLogCard({
<span className="font-mono text-zinc-300">{keySuffixUi || "—"}</span>
</div>
) : null}
{youtubeKeyRejected ? (
<div className="rounded-lg border border-rose-500/30 bg-rose-500/[0.10] px-3 py-2.5 text-xs text-rose-100 ring-1 ring-rose-500/15">
<div className="flex gap-2">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-rose-300" aria-hidden />
<p>
{t(
"YouTube 已拒绝本次 RTMPS 推流。请从 YouTube Studio 当前直播间复制完整串流密钥,保存到当前线路后重新开始;如果密钥确认无误,再检查到 YouTube RTMPS 的网络/代理。",
"YouTube rejected this RTMPS publish. Copy the full stream key for the current live event from YouTube Studio, save it to this lane, then start again; if the key is correct, check network/proxy access to YouTube RTMPS.",
)}
</p>
</div>
</div>
) : null}
{primaryUrl ? (
<div className="rounded-lg border border-violet-500/20 bg-violet-500/[0.06] px-3 py-2.5">
<div className="flex flex-wrap items-center justify-between gap-2">
@ -321,9 +370,12 @@ export function LiveProcessLiveLogCard({
className="inline-flex items-center gap-1.5 rounded-lg bg-violet-500/20 px-3 py-1.5 text-xs font-medium text-violet-100 ring-1 ring-violet-500/35 transition hover:bg-violet-500/30"
>
<ExternalLink className="h-3.5 w-3.5 shrink-0 opacity-90" />
{primaryRoomId || t("打开抖音直播页", "Open Douyin live")}
{primarySourceLabel || t("打开抖音直播页", "Open Douyin live")}
</a>
</div>
{primaryRoomId && primarySourceLabel && !primarySourceLabel.includes(primaryRoomId) ? (
<p className="mt-2 font-mono text-[10px] text-zinc-600">room:{primaryRoomId}</p>
) : null}
{douyinHints.length > 1 && roomFromLog ? (
<p className="mt-2 text-[10px] text-zinc-600">
{t("配置中还有", "Also in config:")}{" "}

View File

@ -43,6 +43,57 @@ export function extractDouyinLiveUrls(urlIni: string): string[] {
return Array.from(new Set(out)).slice(0, 16);
}
function cleanDouyinSourceTitle(value: string): string {
let text = (value || "").trim().replace(/^[\s"'`[\]()()【】]+|[\s"'`[\]()()【】]+$/g, "");
text = text.replace(/^(?:主播|房间名|直播间|抖音源|源站|标题)\s*[::]\s*/i, "");
text = text.replace(/https?:\/\/(?:www\.)?live\.douyin\.com\/[a-zA-Z0-9_-]+/gi, "");
text = text.replace(/(?:等待直播|正在直播|直播中|已开播|开始推流|主播已下播|下播|录制中|推流中).*$/i, "");
text = text.trim().replace(/^[\s,,;;||\-—::]+|[\s,,;;||\-—::]+$/g, "");
if (!text || /^[-—_无未知]+$/i.test(text)) return "";
if (/^(unknown|null|undefined|none|nan)$/i.test(text)) return "";
if (/live\.douyin\.com/i.test(text)) return "";
if (/^\d{5,}$/.test(text)) return "";
if (/^(监测|格式|错误|无录制任务)/.test(text)) return "";
return text.slice(0, 48);
}
export function extractDouyinSourceTitleFromUrlLines(urlIni: string): string {
for (const line of urlIni.split(/\r?\n/)) {
const raw = line.trim();
if (!raw || raw.startsWith("#")) continue;
const match = raw.match(/https?:\/\/(?:www\.)?live\.douyin\.com\/[a-zA-Z0-9_-]+/i);
if (!match || match.index == null) continue;
const tail = raw.slice(match.index + match[0].length);
const fromTail = cleanDouyinSourceTitle(tail);
if (fromTail) return fromTail;
const parts = raw.split(/[,,||]/, 2);
if (parts.length > 1) {
const fromPart = cleanDouyinSourceTitle(parts[1]);
if (fromPart) return fromPart;
}
}
return "";
}
export function extractDouyinSourceTitleFromLog(logText: string): string {
const lines = logText.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).slice(-160);
for (let i = lines.length - 1; i >= 0; i -= 1) {
const line = lines[i];
const labeled = line.match(/(?:主播|房间名|直播间|抖音源|源站|标题)\s*[::]\s*(.{1,80})/i);
const status = line.match(/(?:序号\s*\d+\s*)?(.{1,80}?)\s*(?:等待直播|正在直播|直播中|已开播|开始推流|主播已下播|下播|录制中|推流中)/i);
const title = cleanDouyinSourceTitle(labeled?.[1] || status?.[1] || "");
if (title) return title;
}
return "";
}
export function douyinSourceDisplayFrom(urlIni: string, logText = ""): string {
const title = extractDouyinSourceTitleFromUrlLines(urlIni) || extractDouyinSourceTitleFromLog(logText);
if (title) return title;
const roomId = extractDouyinCurrentRoomFromLog(logText) || extractDouyinRoomHints(urlIni)[0] || "";
return roomId ? `抖音直播间 ${roomId}` : "";
}
/** 从进程日志中解析「当前」抖音房间号(取文本中最后一次出现的 live.douyin.com/xxx) */
export function extractDouyinCurrentRoomFromLog(logText: string): string | null {
if (!logText) return null;
@ -85,7 +136,7 @@ export function parseYoutubeIniFields(content: string): YoutubeIniFields {
let key = "";
let rtmps = true;
let bitrate = "";
let fastAudio = false;
let fastAudio = true;
const lines = content.split(/\r?\n/);
let inYoutube = false;
for (const line of lines) {

View File

@ -17,6 +17,32 @@ const YOUTUBE_PRO_PM2_PREFIX = "youtube2__";
const PM2_SANITIZE_RE = /[^a-zA-Z0-9_.-]+/g;
const RESERVED_PRO_PM2_NAMES = new Set(["youtube", "douyin_youtube", "tiktok", "obs", "web"]);
export function isBrokenYoutubeProLaneName(value: string | undefined): boolean {
const s = (value || "").trim();
return (
!s ||
/\?{2,}/.test(s) ||
/?{2,}/.test(s) ||
/<2F>/.test(s) ||
/锟|绾胯矾|çº|è·|Â/.test(s) ||
/^(undefined|null|nan)$/i.test(s)
);
}
export function cleanYoutubeProLaneName(value: string | undefined, index: number): string {
const raw = (value || "").trim();
if (!isBrokenYoutubeProLaneName(raw)) return raw;
const laneNo = raw.match(/\d+/)?.[0] || String(Math.max(0, index) + 1);
return `线路 ${laneNo}`;
}
export function cleanYoutubeProChannelNames(channels: YoutubeProChannel[]): YoutubeProChannel[] {
return channels.map((channel, index) => ({
...channel,
name: cleanYoutubeProLaneName(channel.name, index),
}));
}
export function sanitizeYoutubePm2Name(value: string): string {
return (value || "").trim().replace(PM2_SANITIZE_RE, "_");
}
@ -36,16 +62,17 @@ export function resolveYoutubeProChannelPm2(channel: Pick<YoutubeProChannel, "id
export function parseYoutubeProChannelList(raw: unknown): YoutubeProChannel[] {
if (!Array.isArray(raw)) return [];
return raw
.map((x) => migrateRow(x as Record<string, unknown>))
const parsed = raw
.map((x, index) => migrateRow(x as Record<string, unknown>, index))
.filter((c): c is YoutubeProChannel => c !== null);
return cleanYoutubeProChannelNames(parsed);
}
function migrateRow(x: Record<string, unknown>): YoutubeProChannel | null {
function migrateRow(x: Record<string, unknown>, index = 0): YoutubeProChannel | null {
if (!x || typeof x !== "object") return null;
const id = String(x.id || "").trim();
if (!id) return null;
const name = String(x.name || "").trim() || id;
const name = cleanYoutubeProLaneName(typeof x.name === "string" ? x.name : "", index);
return {
id,
name,
@ -62,7 +89,8 @@ function safeParse(raw: string | null): YoutubeProChannel[] {
try {
const v = JSON.parse(raw) as unknown;
if (!Array.isArray(v)) return [];
return v.map((x) => migrateRow(x as Record<string, unknown>)).filter((c): c is YoutubeProChannel => c !== null);
const parsed = v.map((x, index) => migrateRow(x as Record<string, unknown>, index)).filter((c): c is YoutubeProChannel => c !== null);
return cleanYoutubeProChannelNames(parsed);
} catch {
return [];
}
@ -86,7 +114,7 @@ export function loadYoutubeProChannels(): YoutubeProChannel[] {
export function saveYoutubeProChannels(channels: YoutubeProChannel[]): void {
if (typeof window === "undefined") return;
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(channels));
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(cleanYoutubeProChannelNames(channels)));
}
const YOUTUBE_PRO_SYNC_PATHS = ["/hub/youtube_pro_channels", "/youtube_pro_channels"] as const;
@ -96,6 +124,10 @@ export type YoutubeProChannelsRemoteResult = {
channels: YoutubeProChannel[];
};
export type YoutubeProChannelsSyncOptions = {
force?: boolean;
};
/** 从服务器拉多频道列表(依次尝试 /hub 与根路径,兼容反代未转发 /hub 的情况) */
export async function fetchYoutubeProChannelsRemote(
fetchJson: <T,>(path: string, init?: RequestInit) => Promise<T>,
@ -114,14 +146,16 @@ export async function fetchYoutubeProChannelsRemote(
export async function pushYoutubeProChannelsRemote(
fetchJson: <T,>(path: string, init?: RequestInit) => Promise<T>,
channels: YoutubeProChannel[],
options: YoutubeProChannelsSyncOptions = {},
): Promise<void> {
let last: Error | null = null;
const cleanChannels = cleanYoutubeProChannelNames(channels);
for (const path of YOUTUBE_PRO_SYNC_PATHS) {
try {
const data = await fetchJson<{ neko?: { ok?: boolean; reason?: string; desired?: number; current?: number | string | null } }>(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ channels }),
body: JSON.stringify({ channels: cleanChannels, force: !!options.force }),
});
if (data.neko?.ok === false) {
const desired = data.neko.desired ? ` desired=${data.neko.desired}` : "";

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{5052:function(n,e,u){Promise.resolve().then(u.bind(u,7340))},7340:function(n,e,u){"use strict";u.r(e),u.d(e,{default:function(){return t.Z}});var t=u(7644)}},function(n){n.O(0,[500,166,246,644,971,117,744],function(){return n(n.s=5052)}),_N_E=n.O()}]);

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[851],{2276:function(n,e,u){Promise.resolve().then(u.bind(u,316))},316:function(n,e,u){"use strict";u.r(e),u.d(e,{default:function(){return t.Z}});var t=u(7644)}},function(n){n.O(0,[500,166,246,644,971,117,744],function(){return n(n.s=2276)}),_N_E=n.O()}]);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -2,6 +2,6 @@
3:I[3946,["500","static/chunks/500-ea37cc8de90441f7.js","246","static/chunks/246-a56380dcf5ea0340.js","357","static/chunks/app/android/page-69ff6e74a15b80d9.js"],"default",1]
4:I[4707,[],""]
5:I[6423,[],""]
0:["YkrzWLM94wlN48IcTrahE",[[["",{"children":["android",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["android",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","android","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/3cc8f8b1e17f311a.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
0:["0T-XrNk19a9ZMkGFefL9K",[[["",{"children":["android",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["android",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","android","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]]
1:null

File diff suppressed because one or more lines are too long

View File

@ -2,6 +2,6 @@
3:I[6367,["500","static/chunks/500-ea37cc8de90441f7.js","246","static/chunks/246-a56380dcf5ea0340.js","443","static/chunks/app/console/page-db00fd3a990c6a05.js"],"default",1]
4:I[4707,[],""]
5:I[6423,[],""]
0:["YkrzWLM94wlN48IcTrahE",[[["",{"children":["console",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["console",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","console","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/3cc8f8b1e17f311a.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
0:["0T-XrNk19a9ZMkGFefL9K",[[["",{"children":["console",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["console",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","console","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]]
1:null

File diff suppressed because one or more lines are too long

View File

@ -1,7 +1,7 @@
2:I[9107,[],"ClientPageRoot"]
3:I[1499,["500","static/chunks/500-ea37cc8de90441f7.js","787","static/chunks/787-c8a125ea62aa3908.js","246","static/chunks/246-a56380dcf5ea0340.js","931","static/chunks/app/page-961397b3cef5e0c4.js"],"default",1]
3:I[7340,["500","static/chunks/500-ea37cc8de90441f7.js","166","static/chunks/166-6b01e1456a874782.js","246","static/chunks/246-a56380dcf5ea0340.js","644","static/chunks/644-fd6fe0f98d73fa51.js","931","static/chunks/app/page-505467ca9505824f.js"],"default",1]
4:I[4707,[],""]
5:I[6423,[],""]
0:["YkrzWLM94wlN48IcTrahE",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/3cc8f8b1e17f311a.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
0:["0T-XrNk19a9ZMkGFefL9K",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]]
1:null

File diff suppressed because one or more lines are too long

View File

@ -2,6 +2,6 @@
3:I[3398,["500","static/chunks/500-ea37cc8de90441f7.js","246","static/chunks/246-a56380dcf5ea0340.js","6","static/chunks/app/shellcrash/page-766863ba520c08ee.js"],"default",1]
4:I[4707,[],""]
5:I[6423,[],""]
0:["YkrzWLM94wlN48IcTrahE",[[["",{"children":["shellcrash",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["shellcrash",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","shellcrash","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/3cc8f8b1e17f311a.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
0:["0T-XrNk19a9ZMkGFefL9K",[[["",{"children":["shellcrash",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["shellcrash",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","shellcrash","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]]
1:null

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,7 @@
2:I[9107,[],"ClientPageRoot"]
3:I[316,["500","static/chunks/500-ea37cc8de90441f7.js","166","static/chunks/166-6b01e1456a874782.js","246","static/chunks/246-a56380dcf5ea0340.js","644","static/chunks/644-fd6fe0f98d73fa51.js","851","static/chunks/app/youtube-events/page-505c03a44db53360.js"],"default",1]
4:I[4707,[],""]
5:I[6423,[],""]
0:["0T-XrNk19a9ZMkGFefL9K",[[["",{"children":["youtube-events",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["youtube-events",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","youtube-events","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]]
1:null

Binary file not shown.

View File

@ -49,6 +49,7 @@ from src.control_plane import (
load_hardware_profile,
query_services,
read_root_file,
neko_instance_action,
service_action,
stack_summary,
system_snapshot,
@ -65,13 +66,24 @@ from src.config_governance import (
restore_backup,
save_managed_file as governed_save_managed_file,
)
from src.hub_kv_store import get_youtube_pro_channels, set_youtube_pro_channels
from src.douyin_source_display import extract_douyin_source_meta
from src.hub_kv_store import get_youtube_pro_channels, merge_youtube_pro_channels, set_youtube_pro_channels
from src.hub_routes import YoutubeProChannelsBody, configure_hub, router as hub_router
from src.neko_capacity import ensure_neko_capacity_for_youtube_channels
from src.network_preflight import format_preflight_message, youtube_network_preflight
from src.network_preflight import format_preflight_message, system_network_probe, youtube_network_preflight
from src.process_runtime_status import summarize_process_activity, tail_log_text
from src.process_runtime_status import coerce_declared_process_status, process_family
from src.runtime_bootstrap import raise_nofile_limit
from src.ops_center import create_system_snapshot, studio_ops_summary
from src.studio_control import (
delete_wol_device,
list_serial_ports,
list_wol_devices,
probe_wol_devices,
send_serial_command,
send_wake_on_lan,
upsert_wol_device,
)
from src.web_process_backend import WebProcessBackend, force_kill_ffmpeg, strip_ansi_codes
from src.youtube_pro_runtime import (
channel_pm2_name,
@ -80,6 +92,17 @@ from src.youtube_pro_runtime import (
managed_youtube_ini_relpath_for_pm2,
validate_youtube_runtime_files,
)
from src.youtube_config_paths import resolve_youtube_style_config_paths
from src.youtube_live_store import (
close_live_event,
get_live_event,
ingest_browser_telemetry,
list_live_events,
record_control_action,
record_process_observation,
youtube_live_summary,
)
from src.youtube_quality_guard import build_youtube_quality_guard_report
# ---------------- 配置(根目录结构) ----------------
BASE_DIR = Path(__file__).parent.resolve()
@ -88,6 +111,8 @@ DEFAULT_LOG_DIR = BASE_DIR / ".pm2" / "logs"
CONSOLE_OUT = BASE_DIR / "web-console" / "out"
MAX_LOG_LINES = 300
YOUTUBE_EVENT_STATUS_OBSERVE_SECONDS = 5.0
_YOUTUBE_EVENT_STATUS_CACHE: dict[str, float] = {}
MAX_TIKTOK_REPLAY_UPLOAD = 2 * 1024 * 1024 * 1024
_TIKTOK_REPLAY_EXT = frozenset({".mp4", ".mkv", ".ts", ".flv", ".mov", ".m4v", ".webm"})
@ -385,6 +410,70 @@ def _validate_youtube_runtime_files(process: str) -> list[str]:
return validate_youtube_runtime_files(BASE_DIR, CONFIG_DIR, process, get_youtube_pro_channels())
def _read_text_if_file(path: str | Path) -> str:
try:
file_path = Path(path)
if file_path.is_file():
return file_path.read_text(encoding="utf-8", errors="ignore")
except OSError:
pass
return ""
def _youtube_event_context(process: str) -> dict[str, str]:
youtube_path, url_path = resolve_youtube_style_config_paths(BASE_DIR, process)
channel_id = ""
channel_name = ""
for channel in get_youtube_pro_channels():
if channel_pm2_name(channel) == process:
channel_id = str(channel.get("id") or "")
channel_name = str(channel.get("name") or "")
break
return {
"youtube_ini_text": _read_text_if_file(youtube_path),
"url_lines": _read_text_if_file(url_path),
"channel_id": channel_id,
"channel_name": channel_name,
"mode": "pro" if process.startswith("youtube2__") else "single",
}
def _youtube_source_meta(process: str, recent_log: str = "") -> dict[str, Any]:
sc = script_for_pm2_or_pro(process) or ""
if not sc or not is_youtube_script(sc):
return {}
ctx = _youtube_event_context(process)
return extract_douyin_source_meta(ctx.get("url_lines", ""), recent_log)
async def _record_youtube_control_event(process: str, action: str, script: str, note: str = "") -> None:
if not script or not is_youtube_script(script):
return
ctx = _youtube_event_context(process)
await asyncio.to_thread(
record_control_action,
process,
action,
script=script,
url_lines=ctx["url_lines"],
youtube_ini_text=ctx["youtube_ini_text"],
channel_id=ctx["channel_id"],
channel_name=ctx["channel_name"],
mode=ctx["mode"],
note=note,
)
async def _record_youtube_status_observation(process: str, payload: dict[str, Any]) -> None:
now = time.time()
last = _YOUTUBE_EVENT_STATUS_CACHE.get(process, 0.0)
if now - last < YOUTUBE_EVENT_STATUS_OBSERVE_SECONDS:
return
_YOUTUBE_EVENT_STATUS_CACHE[process] = now
ctx = _youtube_event_context(process)
await asyncio.to_thread(record_process_observation, process, payload, url_lines=ctx["url_lines"])
async def _process_runtime_identity(process: str) -> tuple[int, int | None]:
try:
pid = await process_backend.process_pid(process)
@ -569,13 +658,99 @@ async def alias_youtube_pro_channels_get() -> dict:
@app.post("/youtube_pro_channels", include_in_schema=False)
async def alias_youtube_pro_channels_post(body: YoutubeProChannelsBody):
try:
if body.force:
set_youtube_pro_channels(body.channels)
channels = get_youtube_pro_channels()
else:
channels = merge_youtube_pro_channels(body.channels)
except ValueError as exc:
return JSONResponse({"error": str(exc)}, status_code=400)
except sqlite3.Error as exc:
return JSONResponse({"error": _youtube_pro_store_error(exc)}, status_code=500)
capacity = await asyncio.to_thread(ensure_neko_capacity_for_youtube_channels, BASE_DIR, body.channels)
return {"message": "ok", "neko": capacity}
capacity = await asyncio.to_thread(ensure_neko_capacity_for_youtube_channels, BASE_DIR, channels)
return {"message": "ok", "channels": channels, "neko": capacity}
@app.get("/youtube/live/summary", include_in_schema=False)
async def alias_youtube_live_summary() -> dict[str, Any]:
return await asyncio.to_thread(youtube_live_summary)
@app.get("/youtube/live/events", include_in_schema=False)
async def alias_youtube_live_events(
status: str = "",
process: str = "",
limit: int = 50,
offset: int = 0,
) -> dict[str, Any]:
return await asyncio.to_thread(
list_live_events,
status=status,
process=process,
limit=limit,
offset=offset,
)
@app.get("/youtube/live/events/{event_id}", include_in_schema=False)
async def alias_youtube_live_event_detail(event_id: str):
event = await asyncio.to_thread(get_live_event, event_id)
if not event:
return JSONResponse({"error": "live event not found"}, status_code=404)
return {"event": event}
@app.post("/youtube/live/events/{event_id}/close", include_in_schema=False)
async def alias_youtube_live_event_close(event_id: str, body: dict[str, Any]):
result = await asyncio.to_thread(close_live_event, event_id, reason=str(body.get("reason") or "manual"))
if not result:
return JSONResponse({"error": "live event not found"}, status_code=404)
return result
@app.post("/youtube/live/ingest", include_in_schema=False)
async def alias_youtube_live_ingest(payload: dict[str, Any]) -> dict[str, Any]:
return await asyncio.to_thread(ingest_browser_telemetry, payload)
async def _youtube_quality_guard_payload() -> dict[str, Any]:
entries = [dict(p) for p in process_monitor_entries() if _process_monitor_family_matches(p, "youtube")]
names = [str(entry.get("pm2") or "").strip() for entry in entries if str(entry.get("pm2") or "").strip()]
infos = await process_backend.process_infos(names)
async def build_row(entry: dict[str, str]) -> dict[str, Any]:
name = str(entry.get("pm2") or "").strip()
info = _coerce_local_configured_process(name, infos.get(name) or {})
recent_log, recent_error = await asyncio.gather(
read_log_path_normalized(info.get("out_path"), 80),
read_log_path_normalized(info.get("err_path"), 80),
)
snapshot = await _process_monitor_snapshot_from_info(entry, info, light=False)
snapshot["recent_log"] = recent_log[-12000:]
snapshot["recent_error"] = recent_error[-8000:]
return snapshot
rows = await asyncio.gather(*(build_row(entry) for entry in entries), return_exceptions=True)
clean_rows = [row for row in rows if isinstance(row, dict)]
configs: dict[str, dict[str, str]] = {}
for row in clean_rows:
process = str(row.get("pm2") or "")
if not process:
continue
with suppress(Exception):
configs[process] = _youtube_event_context(process)
live = await asyncio.to_thread(youtube_live_summary)
return build_youtube_quality_guard_report(clean_rows, live_summary=live, config_by_process=configs)
@app.get("/youtube/quality_guard", include_in_schema=False)
async def alias_youtube_quality_guard() -> dict[str, Any]:
return await _youtube_quality_guard_payload()
@app.get("/hub/youtube/quality_guard", include_in_schema=False)
async def hub_youtube_quality_guard() -> dict[str, Any]:
return await _youtube_quality_guard_payload()
app.add_middleware(
@ -630,6 +805,39 @@ class ServiceActionPostBody(BaseModel):
action: str = Field(..., pattern="^(install|start|stop|restart|status|uninstall|upgrade)$")
class NekoInstanceActionBody(BaseModel):
id: int = Field(..., ge=1, le=64)
action: str = Field(..., pattern="^(status|start|stop|restart|delete)$")
class WolWakeBody(BaseModel):
mac: str = Field(..., min_length=1, max_length=32)
broadcast: str = Field(default="255.255.255.255", min_length=7, max_length=15)
port: int = Field(default=9, ge=1, le=65535)
class WolDeviceBody(BaseModel):
name: str = Field(default="", max_length=120)
mac: str = Field(..., min_length=1, max_length=32)
ip: str = Field(default="", max_length=15)
class WolDeleteBody(BaseModel):
mac: str = Field(..., min_length=1, max_length=32)
class SerialCommandBody(BaseModel):
port: str = Field(..., min_length=1, max_length=120)
command: str = Field(..., min_length=1, max_length=1000)
baudrate: int = Field(default=115200, ge=1200, le=1000000)
timeout: float = Field(default=2.0, ge=0.2, le=10.0)
append_crlf: bool = True
class StudioSnapshotBody(BaseModel):
reason: str = Field(default="manual", max_length=80)
class ShellCrashApplyProfileBody(BaseModel):
path: str = Field(default=SHELLCRASH_DEFAULT_PROFILE, min_length=1, max_length=240)
target_node: str = Field(default=SHELLCRASH_DEFAULT_NODE, min_length=1, max_length=200)
@ -798,6 +1006,16 @@ async def get_stack_services():
return {"services": await query_services()}
@app.get("/hub/network/system_probe")
async def get_hub_network_system_probe(include_proxy: bool = Query(True)):
return await asyncio.to_thread(system_network_probe, include_proxy=include_proxy)
@app.get("/network/system_probe")
async def get_network_system_probe(include_proxy: bool = Query(True)):
return await asyncio.to_thread(system_network_probe, include_proxy=include_proxy)
@app.get("/android/devices")
async def get_android_devices():
return {
@ -1042,6 +1260,90 @@ async def run_service_action_post(body: ServiceActionPostBody):
return JSONResponse({"error": str(exc)}, status_code=400)
@app.post("/neko/instance_action")
async def run_neko_instance_action(body: NekoInstanceActionBody):
try:
return await neko_instance_action(body.id, body.action)
except ValueError as exc:
return JSONResponse({"error": str(exc)}, status_code=400)
except RuntimeError as exc:
return JSONResponse({"error": str(exc)}, status_code=500)
@app.post("/studio/wol/wake")
async def post_studio_wol_wake(body: WolWakeBody):
try:
return await asyncio.to_thread(send_wake_on_lan, body.mac, body.broadcast, body.port)
except ValueError as exc:
return JSONResponse({"error": str(exc)}, status_code=400)
except OSError as exc:
return JSONResponse({"error": str(exc)}, status_code=500)
@app.get("/studio/wol/devices")
async def get_studio_wol_devices(refresh: bool = Query(False)):
if refresh:
return await asyncio.to_thread(probe_wol_devices, BASE_DIR)
return {"devices": await asyncio.to_thread(list_wol_devices, BASE_DIR)}
@app.post("/studio/wol/devices/probe")
async def post_studio_wol_probe():
return await asyncio.to_thread(probe_wol_devices, BASE_DIR)
@app.post("/studio/wol/devices")
async def post_studio_wol_device(body: WolDeviceBody):
try:
device = await asyncio.to_thread(upsert_wol_device, body.name, body.mac, body.ip, BASE_DIR)
return {"message": "Device saved", "device": device, "devices": await asyncio.to_thread(list_wol_devices, BASE_DIR)}
except ValueError as exc:
return JSONResponse({"error": str(exc)}, status_code=400)
@app.post("/studio/wol/devices/delete")
async def post_studio_wol_device_delete(body: WolDeleteBody):
try:
return await asyncio.to_thread(delete_wol_device, body.mac, BASE_DIR)
except ValueError as exc:
return JSONResponse({"error": str(exc)}, status_code=400)
@app.get("/studio/serial/ports")
async def get_studio_serial_ports():
return {"ports": await asyncio.to_thread(list_serial_ports)}
@app.post("/studio/serial/command")
async def post_studio_serial_command(body: SerialCommandBody):
try:
return await asyncio.to_thread(
send_serial_command,
body.port,
body.command,
body.baudrate,
body.timeout,
body.append_crlf,
)
except (RuntimeError, ValueError, OSError) as exc:
return JSONResponse({"error": str(exc)}, status_code=400)
@app.get("/studio/ops/summary")
async def get_studio_ops_summary(refresh: bool = Query(False)):
services = await query_services()
deployment = await asyncio.to_thread(deployment_report)
return await asyncio.to_thread(studio_ops_summary, services, deployment, BASE_DIR, refresh=refresh)
@app.post("/studio/ops/snapshot")
async def post_studio_ops_snapshot(body: StudioSnapshotBody):
try:
return await asyncio.to_thread(create_system_snapshot, BASE_DIR, reason=body.reason)
except OSError as exc:
return JSONResponse({"error": str(exc)}, status_code=500)
@app.post("/shellcrash/apply_profile")
async def post_shellcrash_apply_profile(body: ShellCrashApplyProfileBody):
try:
@ -1445,6 +1747,7 @@ async def _process_monitor_snapshot_from_info(
log_age_seconds=_newest_log_age_seconds(info.get("out_path"), info.get("err_path")),
ffmpeg_pids=ffmpeg_pids,
)
source_meta = _youtube_source_meta(name, recent_log)
return {
"pm2": name,
"script": str(entry.get("script") or ""),
@ -1454,6 +1757,7 @@ async def _process_monitor_snapshot_from_info(
"business_note": str(activity.get("business_note") or ""),
"ffmpeg_active": bool(activity.get("ffmpeg_active")),
"is_pushing": bool(activity.get("is_pushing")),
**source_meta,
}
@ -1483,6 +1787,8 @@ async def start(process: str = Query(..., description="进程名")):
return JSONResponse({"output": preflight_message}, status_code=400)
stopped = await _stop_other_hdmi_sink_processes(process)
output = await process_backend.start(process, sc)
with suppress(Exception):
await _record_youtube_control_event(process, "start", sc, preflight_message)
prefix = (preflight_message + "\n") if preflight_message else ""
if stopped:
prefix += "已停止其它占用 HDMI 链路的进程: " + "、".join(stopped) + "\n"
@ -1499,6 +1805,7 @@ async def stop(process: str = Query(..., description="进程名")):
if not is_valid_control_process(process):
return JSONResponse({"output": f"无效进程名: {process}"}, status_code=400)
sc = script_for_pm2_or_pro(process) or ""
root_pid, root_pgid = await _process_runtime_identity(process)
pm2_output = await process_backend.stop(process)
@ -1515,6 +1822,8 @@ async def stop(process: str = Query(..., description="进程名")):
if str(post_info.get("process_status") or "").lower() in {"online", "running"}:
with suppress(ProcessLookupError, PermissionError, OSError):
os.kill(root_pid, signal.SIGKILL)
with suppress(Exception):
await _record_youtube_control_event(process, "stop", sc, "manual stop")
return JSONResponse(
{
@ -1548,6 +1857,8 @@ async def restart(process: str = Query(..., description="进程名")):
if not process.startswith("web"):
await force_kill_ffmpeg(process, BASE_DIR, root_pid=root_pid, root_pgid=root_pgid)
output = await process_backend.restart(process, sc)
with suppress(Exception):
await _record_youtube_control_event(process, "restart", sc, preflight_message)
prefix = (preflight_message + "\n") if preflight_message else ""
if stopped:
prefix += "已停止其它占用 HDMI 链路的进程: " + "、".join(stopped) + "\n"
@ -1586,6 +1897,19 @@ async def status(process: str = Query(..., description="进程名")):
log_age_seconds=_newest_log_age_seconds(info.get("out_path"), info.get("err_path")),
ffmpeg_pids=await process_backend.live_ffmpeg_pids(process),
)
sc = script_for_pm2_or_pro(process) or ""
if sc and is_youtube_script(sc):
with suppress(Exception):
await _record_youtube_status_observation(
process,
{
"source": "status_api",
"process_status": str(info.get("process_status") or ""),
"recent_log": recent_log[-4000:],
"recent_error": recent_error[-2000:],
**activity,
},
)
if info["process_status"] == "not_found":
recent_log = _not_found_hint(process) + "\n"
@ -1596,6 +1920,7 @@ async def status(process: str = Query(..., description="进程名")):
recent_error = ""
full_status = configured_hint
source_meta = _youtube_source_meta(process, recent_log)
return JSONResponse(
{
"raw_status": full_status,
@ -1603,6 +1928,7 @@ async def status(process: str = Query(..., description="进程名")):
"recent_log": recent_log,
"recent_error": recent_error,
**activity,
**source_meta,
}
)
@ -1683,6 +2009,14 @@ async def shellcrash_page():
return await index()
@app.get("/youtube-events", include_in_schema=False)
async def youtube_events_page():
route_file = _console_route_html("youtube-events")
if route_file:
return FileResponse(route_file, media_type="text/html; charset=utf-8")
return await index()
@app.get("/console", include_in_schema=False)
async def console_page():
route_file = _console_route_html("console")