Harden YouTube unmanned live stack and hide advanced console panels.
Fix Pro config SSOT, event FSM, FFmpeg error tiers, relay heartbeat, and ingest auth while keeping relay snapshot, quality guard, and event hub hidden in the UI. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
010256f507
commit
9888f1daad
6
d2ypp2/.gitignore
vendored
6
d2ypp2/.gitignore
vendored
@ -9,8 +9,8 @@ develop-eggs/
|
||||
dist/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
/lib/
|
||||
/lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
@ -67,6 +67,7 @@ downloads/
|
||||
backup_config/
|
||||
.deploy_logs/
|
||||
.process_runner/
|
||||
runtime/
|
||||
.pm2/
|
||||
tmp/
|
||||
temp/
|
||||
@ -117,3 +118,4 @@ desktop.ini
|
||||
cursor/
|
||||
cursor*.md
|
||||
*.tmp
|
||||
artifacts/
|
||||
|
||||
@ -53,6 +53,11 @@ SHELLCRASH_NEKO_PROXY_NODE=proxycheap
|
||||
# NEKO_BROWSER_PROXY=
|
||||
NETWORK_PROBE_GOOGLE_URL=https://www.google.com/generate_204
|
||||
NETWORK_PROBE_YOUTUBE_URL=https://www.youtube.com/generate_204
|
||||
|
||||
# YouTube Studio 插件遥测鉴权(留空则关闭鉴权;设置后 extension 需在 chrome.storage.local 写入 liveHubIngestToken)
|
||||
# YOUTUBE_INGEST_TOKEN=change-me
|
||||
# YOUTUBE_INGEST_REQUIRE_AUTH=1
|
||||
# YOUTUBE_PUSH_PROXY_PORT=7890
|
||||
NETWORK_PROBE_DOUYIN_URL=https://live.douyin.com/
|
||||
|
||||
# WireGuard client watchdog: PersistentKeepalive should keep NAT bindings fresh, but some kernels/NICs can wedge.
|
||||
|
||||
@ -5,8 +5,8 @@ key =
|
||||
# 可选:是否使用 RTMPS 加密推流,填 否 则用 RTMP(默认 RTMPS)
|
||||
; rtmps = 否
|
||||
|
||||
# 可选:视频比特率 kbps,YouTube 推荐 4000-6000,默认 4500
|
||||
; bitrate = 4500
|
||||
# 可选:视频比特率 kbps,YouTube 推荐 4000-6000,默认 4000
|
||||
; bitrate = 4000
|
||||
|
||||
# 可选:软编 speed 长期小于 1 时开启——轻量音频链(无 arnndn/长 EQ),减轻 CPU。填 1 或 是
|
||||
; fast_audio = 1
|
||||
|
||||
106
d2ypp2/docs/host04-tuic5-neko-push-status-2026-06-22.md
Normal file
106
d2ypp2/docs/host04-tuic5-neko-push-status-2026-06-22.md
Normal file
@ -0,0 +1,106 @@
|
||||
# 10.88.0.4 / 10.88.0.5 Neko 与 YouTube 推流排查报告
|
||||
|
||||
日期:2026-06-22
|
||||
|
||||
## 结论
|
||||
|
||||
- Neko 浏览器代理和 FFmpeg 推流代理是两条不同链路。
|
||||
- Neko 代理开关打开时,Neko/Chrome 走专用 mixed listener:`host.docker.internal:7894`,节点固定为 `proxycheap`。
|
||||
- FFmpeg 推流不走 Neko listener,推流通过 `proxychains` 连接 `socks5://127.0.0.1:7890`,实际出口由 ShellCrash 主选择器决定。
|
||||
- `proxycheap` 已限速,不能用于推流吞吐判断;推流验证已改用 ShellCrash 主选择器 `1d2da142-singbox_tuic5`。
|
||||
|
||||
## 10.88.0.4 已改内容
|
||||
|
||||
- `config/system-stack.env`
|
||||
- `NEKO_SHELLCRASH_PROXY_PORT=7894`
|
||||
- `SHELLCRASH_NEKO_PROXY_NODE=proxycheap`
|
||||
- `NEKO_BROWSER_PROXY=http://host.docker.internal:7894`
|
||||
- `SHELLCRASH_ATTACH_FFMPEG=auto`
|
||||
- `config/hardware.env`
|
||||
- `LIVE_VIDEO_ENCODER=h264_vaapi`
|
||||
- `LIVE_VAAPI_QP=24`
|
||||
- ShellCrash API 选择器
|
||||
- `GLOBAL -> 1d2da142-singbox_tuic5`
|
||||
- `dialer -> 1d2da142-singbox_tuic5`
|
||||
- `🚀 节点选择 -> 1d2da142-singbox_tuic5`
|
||||
- 运行时环境
|
||||
- 重启过 `live-console`,让进程环境从磁盘重新加载,修正旧的 `SHELLCRASH_NEKO_PROXY_NODE=5d723acc-singbox_tuic3`。
|
||||
|
||||
## 当前 .4 状态
|
||||
|
||||
最后验证时:
|
||||
|
||||
- 线路 1:`youtube2__ch_mpwri36r_z5lm2`
|
||||
- `process_status=online`
|
||||
- `business_status=waiting_source`
|
||||
- `ffmpeg_active=false`
|
||||
- `is_pushing=false`
|
||||
- 结论:进程在线,但没有拿到可推的上游直播源,所以没有实际 FFmpeg 推流。
|
||||
- 线路 2:`youtube2__ch_mpyvqkc0_gj63k`
|
||||
- `process_status=online`
|
||||
- `business_status=streaming`
|
||||
- `ffmpeg_active=true`
|
||||
- `is_pushing=true`
|
||||
- `ffmpeg_speed=1.0`
|
||||
- FFmpeg 参数:`h264_vaapi -rc_mode CQP -qp 24`
|
||||
- FFmpeg socket:连接 `127.0.0.1:7890`,即通过 ShellCrash 主代理推流。
|
||||
|
||||
## “显示推流中但实际没有推流”的原因
|
||||
|
||||
之前存在两个问题叠加:
|
||||
|
||||
1. 真实推流失败时,PM2/local 进程仍可能是 `online`,但 FFmpeg worker 已退出或没有启动。
|
||||
2. 前端部分状态显示把 `process_status=online` 当成活跃信号,导致在线进程看起来像“推流中”。
|
||||
|
||||
正确判断必须以这些字段为准:
|
||||
|
||||
- `is_pushing=true`
|
||||
- 或 `business_status=streaming/relay_slow`
|
||||
- 并结合 `ffmpeg_active=true`、`ffmpeg_frame/speed` 判断真实转推。
|
||||
|
||||
`process_status=online` 只能表示 Python 监控进程还活着,不能表示正在推流。
|
||||
|
||||
## 源码修复
|
||||
|
||||
- `web-console/components/live-product/LiveProcessLiveLogCard.tsx`
|
||||
- 删除 `onlineNow` 对 live metrics 和“推流中”显示的影响。
|
||||
- 不再使用 `monitorRow.is_pushing` 覆盖当前 `/status` 查询结果。
|
||||
- `web-console/components/live-product/LiveYoutubeUnmannedView.tsx`
|
||||
- 线路列表不再因为 `rowOnline` 把 FFmpeg 指标当成 live。
|
||||
- 在线但未推流的状态 badge 改为中性色,不再使用绿色推流态样式。
|
||||
- `tools/remote_patch_host04.py`
|
||||
- 明确拆分:
|
||||
- `SHELLCRASH_PUSH_NODE = "1d2da142-singbox_tuic5"`
|
||||
- `NEKO_PROXY_NODE = "proxycheap"`
|
||||
- 避免以后把 Neko 专用节点误改成推流节点。
|
||||
- `tests/test_live_console_status_ui.py`
|
||||
- 新增回归测试,防止再次把 PM2 online 当成 pushing。
|
||||
- `web.py`
|
||||
- HTML 路由改为 `Cache-Control: no-store`,避免浏览器长期缓存旧 Next HTML 后混用新旧 chunk。
|
||||
- 该改动需要后端下次重启后生效;为避免打断当前 `.4` 推流,本次没有重启 `live-console`。
|
||||
|
||||
## 前端 Application error 处理
|
||||
|
||||
- `.4` 上发现 `web-console/out/_next/static` 残留多个旧 build id 和旧 chunk。
|
||||
- 已清理 `.4/.5` 旧 chunk,仅保留当前 build:
|
||||
- 当前 build id:`gsAjqEJQnJY-VJeXc58CT`
|
||||
- 当前主 chunk:`904-75d9964e1328b442.js`
|
||||
- 旧 chunk:`904-3cb5a9f6d2f9613c.js` 已不再可访问。
|
||||
- 干净 Chrome 访问 `http://10.88.0.4:8001/?view=live_youtube` 可加载页面内容,未捕获客户端异常。
|
||||
- 如果已有浏览器仍显示 `Application error`,原因大概率是浏览器缓存了旧 Next app shell;使用强制刷新或带版本参数 URL:
|
||||
- `http://10.88.0.4:8001/?view=live_youtube&v=20260622-1810`
|
||||
|
||||
## 10.88.0.5 验证
|
||||
|
||||
- Neko listener:`neko-mixed:7894 -> proxycheap`
|
||||
- ShellCrash 主选择器:`GLOBAL/dialer -> 1d2da142-singbox_tuic5`
|
||||
- `config/hardware.env`:`LIVE_VIDEO_ENCODER=h264_vaapi`、`LIVE_VAAPI_QP=24`
|
||||
- 当时状态:
|
||||
- 线路 1:`waiting_source`,未推流。
|
||||
- 线路 2:`streaming`,存在 FFmpeg 推流进程。
|
||||
|
||||
## 操作注意
|
||||
|
||||
- 不要用 `proxycheap` 测推流性能,它只能验证 Neko 浏览器代理可用性。
|
||||
- 推流性能测试必须看 FFmpeg 进程、`127.0.0.1:7890` socket、ShellCrash 主选择器和 `speed=` 日志。
|
||||
- 如果线路显示 `waiting_source`,先查上游抖音直播源是否可用,不要先判断为代理或 YouTube 问题。
|
||||
@ -17,6 +17,8 @@ import shutil
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from src.youtube_runtime import resolve_live_video_encoder
|
||||
from src.youtube_encoder_cache import get_cached_encoder, store_cached_encoder
|
||||
from src.youtube_relay_heartbeat import clear_relay_heartbeat, write_relay_heartbeat
|
||||
|
||||
|
||||
class StreamEnded(Exception):
|
||||
@ -41,6 +43,26 @@ def _youtube_bitrate_triplet(kbps: int) -> tuple[str, str, str]:
|
||||
return f"{n}k", f"{n}k", f"{n * 2}k"
|
||||
|
||||
|
||||
def _bounded_int(value: str | None, default: int, minimum: int, maximum: int) -> int:
|
||||
try:
|
||||
parsed = int(str(value or "").strip())
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return max(minimum, min(parsed, maximum))
|
||||
|
||||
|
||||
def _h264_vaapi_video_args(config: dict[str, str] | None = None) -> tuple[list[str], str]:
|
||||
cfg = config or {}
|
||||
qp_raw = (
|
||||
os.environ.get("LIVE_VAAPI_QP")
|
||||
or os.environ.get("YOUTUBE_VAAPI_QP")
|
||||
or cfg.get("LIVE_VAAPI_QP")
|
||||
or cfg.get("YOUTUBE_VAAPI_QP")
|
||||
)
|
||||
qp = _bounded_int(qp_raw, 24, 18, 32)
|
||||
return ["-rc_mode", "CQP", "-qp", str(qp), "-profile:v", "high"], f"CQP qp={qp}"
|
||||
|
||||
|
||||
def _load_simple_env_file(path: str) -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
if not os.path.isfile(path):
|
||||
@ -335,8 +357,13 @@ def _resolve_youtube_push_proxy(configured: str | None = None) -> str:
|
||||
return value
|
||||
|
||||
auto = os.environ.get("YOUTUBE_PUSH_PROXY_AUTO", "1").strip().lower()
|
||||
if auto not in {"0", "false", "no", "off"} and _is_local_tcp_open("127.0.0.1", 7890):
|
||||
return "socks5://127.0.0.1:7890"
|
||||
proxy_port_raw = os.environ.get("YOUTUBE_PUSH_PROXY_PORT") or os.environ.get("LIVE_YOUTUBE_PUSH_PROXY_PORT") or "7890"
|
||||
try:
|
||||
proxy_port = int(str(proxy_port_raw).strip())
|
||||
except (TypeError, ValueError):
|
||||
proxy_port = 7890
|
||||
if auto not in {"0", "false", "no", "off"} and _is_local_tcp_open("127.0.0.1", proxy_port):
|
||||
return f"socks5://127.0.0.1:{proxy_port}"
|
||||
|
||||
for key in ("https_proxy", "http_proxy", "HTTPS_PROXY", "HTTP_PROXY"):
|
||||
value = (os.environ.get(key) or "").strip()
|
||||
@ -608,6 +635,7 @@ def start_douyin_youtube_ffplay(
|
||||
color_obj,
|
||||
config_file: str | None = None,
|
||||
record_url: str | None = None,
|
||||
fallback_urls: list[str] | None = None,
|
||||
):
|
||||
"""
|
||||
抖音 → YouTube 推流主函数(单路推流)
|
||||
@ -617,6 +645,7 @@ def start_douyin_youtube_ffplay(
|
||||
# ====================== 读取 YouTube 配置 ======================
|
||||
config_file = _resolve_youtube_push_config_file(config_file)
|
||||
_config_dir = os.path.dirname(os.path.abspath(config_file))
|
||||
_script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
rtmps_base = os.environ.get("YOUTUBE_RTMPS_BASE", "rtmps://a.rtmps.youtube.com/live2/")
|
||||
rtmp_base = os.environ.get("YOUTUBE_RTMP_BASE", "rtmp://a.rtmp.youtube.com/live2/")
|
||||
use_rtmps = True
|
||||
@ -702,10 +731,6 @@ def start_douyin_youtube_ffplay(
|
||||
"ingestion error",
|
||||
"access denied",
|
||||
"server returned 403",
|
||||
"client disconnected",
|
||||
"error opening output file",
|
||||
"error opening output files",
|
||||
"error opening output",
|
||||
]
|
||||
# 瞬时错误:结束当前 ffmpeg 进程后由外层循环退避重连
|
||||
TRANSIENT_KEYWORDS = [
|
||||
@ -720,6 +745,10 @@ def start_douyin_youtube_ffplay(
|
||||
"error writing output",
|
||||
"broken pipe",
|
||||
"i/o error",
|
||||
"client disconnected",
|
||||
"error opening output file",
|
||||
"error opening output files",
|
||||
"error opening output",
|
||||
]
|
||||
|
||||
douyin_headers = (
|
||||
@ -741,6 +770,7 @@ def start_douyin_youtube_ffplay(
|
||||
"-preset", "ultrafast", "-tune", "zerolatency", "-profile:v", "high", "-level", "4.0",
|
||||
"-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize,
|
||||
]
|
||||
video_rate_label = f"CBR {b_v}"
|
||||
|
||||
_want_enc = (_hw_env.get("LIVE_VIDEO_ENCODER") or "").strip()
|
||||
_hw_enc_active = False
|
||||
@ -789,40 +819,58 @@ def start_douyin_youtube_ffplay(
|
||||
return False
|
||||
|
||||
if platform.system().lower() == "linux":
|
||||
try:
|
||||
enc = subprocess.run(
|
||||
[ffmpeg_bin, "-hide_banner", "-encoders"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=6,
|
||||
)
|
||||
_encoders_blob = (enc.stdout or "") + (enc.stderr or "")
|
||||
_probe_names: list[str] = []
|
||||
for _name in ("h264_rkmpp", "h264_v4l2m2m", "h264_vaapi", _want_enc):
|
||||
if _name and _name.startswith("h264_") and _name in _encoders_blob and _name not in _probe_names:
|
||||
_probe_names.append(_name)
|
||||
_usable_encoders = {
|
||||
_name for _name in _probe_names
|
||||
if _ffmpeg_encoder_smoke_test(_name)
|
||||
}
|
||||
_selected_enc, _enc_note = resolve_live_video_encoder(
|
||||
_want_enc,
|
||||
_encoders_blob,
|
||||
_machine,
|
||||
has_mpp_service=os.path.exists("/dev/mpp_service"),
|
||||
has_render_node=bool(_vaapi_device),
|
||||
has_v4l2_device=bool(glob.glob("/dev/video*")),
|
||||
usable_encoders=_usable_encoders,
|
||||
)
|
||||
if _enc_note:
|
||||
print(f"[WARN] {_enc_note}")
|
||||
if _selected_enc:
|
||||
codec_v = _selected_enc
|
||||
_cached_enc = get_cached_encoder(_machine, ffmpeg_bin, base_dir=_script_dir)
|
||||
if _cached_enc:
|
||||
codec_v = _cached_enc
|
||||
if codec_v == "h264_vaapi" and _vaapi_device:
|
||||
video_args, video_rate_label = _h264_vaapi_video_args(_hw_env)
|
||||
elif codec_v == "h264_nvenc":
|
||||
video_args = [
|
||||
"-profile:v", "high", "-level", "4.0",
|
||||
"-tune", "ll", "-rc", "cbr", "-b:v", b_v, "-minrate", b_v,
|
||||
"-maxrate", maxrate, "-bufsize", bufsize,
|
||||
]
|
||||
elif codec_v != "libx264":
|
||||
video_args = ["-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize]
|
||||
_hw_enc_active = True
|
||||
print(f"[INFO] 使用 config/hardware.env LIVE_VIDEO_ENCODER={codec_v}(板载硬件编码)")
|
||||
except Exception as e:
|
||||
print(f"[WARN] LIVE_VIDEO_ENCODER 校验失败: {e}")
|
||||
video_rate_label = f"CBR {b_v}"
|
||||
_hw_enc_active = True
|
||||
print(f"[INFO] 使用编码器缓存: {codec_v}")
|
||||
if not _hw_enc_active:
|
||||
try:
|
||||
enc = subprocess.run(
|
||||
[ffmpeg_bin, "-hide_banner", "-encoders"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=6,
|
||||
)
|
||||
_encoders_blob = (enc.stdout or "") + (enc.stderr or "")
|
||||
_probe_names: list[str] = []
|
||||
for _name in ("h264_rkmpp", "h264_v4l2m2m", "h264_vaapi", _want_enc):
|
||||
if _name and _name.startswith("h264_") and _name in _encoders_blob and _name not in _probe_names:
|
||||
_probe_names.append(_name)
|
||||
_usable_encoders = {
|
||||
_name for _name in _probe_names
|
||||
if _ffmpeg_encoder_smoke_test(_name)
|
||||
}
|
||||
_selected_enc, _enc_note = resolve_live_video_encoder(
|
||||
_want_enc,
|
||||
_encoders_blob,
|
||||
_machine,
|
||||
has_mpp_service=os.path.exists("/dev/mpp_service"),
|
||||
has_render_node=bool(_vaapi_device),
|
||||
has_v4l2_device=bool(glob.glob("/dev/video*")),
|
||||
usable_encoders=_usable_encoders,
|
||||
)
|
||||
if _enc_note:
|
||||
print(f"[WARN] {_enc_note}")
|
||||
if _selected_enc:
|
||||
codec_v = _selected_enc
|
||||
video_args = ["-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize]
|
||||
video_rate_label = f"CBR {b_v}"
|
||||
_hw_enc_active = True
|
||||
print(f"[INFO] 使用 config/hardware.env LIVE_VIDEO_ENCODER={codec_v}(板载硬件编码)")
|
||||
except Exception as e:
|
||||
print(f"[WARN] LIVE_VIDEO_ENCODER 校验失败: {e}")
|
||||
|
||||
if not _hw_enc_active:
|
||||
try:
|
||||
@ -842,14 +890,16 @@ def start_douyin_youtube_ffplay(
|
||||
"-tune", "ll", "-rc", "cbr", "-b:v", b_v, "-minrate", b_v,
|
||||
"-maxrate", maxrate, "-bufsize", bufsize,
|
||||
]
|
||||
video_rate_label = f"CBR {b_v}"
|
||||
print("[INFO] 检测到 NVIDIA GPU → 使用 NVENC 硬件加速")
|
||||
except Exception as e:
|
||||
print(f"[WARN] NVENC 检测失败,回退软件编码: {e}")
|
||||
|
||||
store_cached_encoder(_machine, ffmpeg_bin, codec_v, base_dir=_script_dir)
|
||||
|
||||
_filter_threads = "4"
|
||||
|
||||
# ====================== 开源音频处理:背景音乐弱化 + 防版权 ======================
|
||||
_script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
_ffmpeg_cwd = None
|
||||
if fast_audio:
|
||||
print("[INFO] fast_audio=开:使用轻量音频链")
|
||||
@ -913,6 +963,7 @@ def start_douyin_youtube_ffplay(
|
||||
_ffmpeg_pre_input = ["-vaapi_device", _vaapi_device]
|
||||
_vf_pad = f"{_vf_pad},format=nv12,hwupload"
|
||||
_pix_fmt = "vaapi"
|
||||
video_args, video_rate_label = _h264_vaapi_video_args(_hw_env)
|
||||
print(f"[INFO] 使用 VAAPI 设备: {_vaapi_device}")
|
||||
else:
|
||||
print("[WARN] h264_vaapi 缺少 /dev/dri/renderD*,回退到 libx264")
|
||||
@ -921,39 +972,62 @@ def start_douyin_youtube_ffplay(
|
||||
"-preset", "ultrafast", "-tune", "zerolatency", "-profile:v", "high", "-level", "4.0",
|
||||
"-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize,
|
||||
]
|
||||
video_rate_label = f"CBR {b_v}"
|
||||
_hw_enc_active = False
|
||||
_input_path = os.path.normpath(os.path.expanduser(real_url))
|
||||
_input_is_file = os.path.isfile(_input_path)
|
||||
_relay_pm2 = _live_pm2_name() or "youtube"
|
||||
_stats_args = _ffmpeg_stats_args(ffmpeg_bin)
|
||||
print(
|
||||
"[INFO] YouTube Live profile: "
|
||||
f"{'RTMPS' if youtube_rtmp.startswith('rtmps://') else 'RTMP'} | "
|
||||
f"H.264 {codec_v} CBR {b_v} | 720x1280@30 | keyint=2s | AAC 128k/48kHz | real-time input pacing"
|
||||
)
|
||||
if _input_is_file:
|
||||
ffmpeg_command = [
|
||||
ffmpeg_bin, "-y", "-loglevel", "info", "-nostdin",
|
||||
*_stats_args,
|
||||
"-fflags", "+genpts+discardcorrupt",
|
||||
"-err_detect", "ignore_err",
|
||||
"-thread_queue_size", "2048",
|
||||
"-filter_threads", _filter_threads,
|
||||
*_ffmpeg_pre_input,
|
||||
"-re",
|
||||
"-i", _input_path,
|
||||
"-vf", _vf_pad,
|
||||
"-c:v", codec_v,
|
||||
*video_args,
|
||||
*_video_mid,
|
||||
"-pix_fmt", _pix_fmt,
|
||||
"-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "2",
|
||||
"-af", _af_chain,
|
||||
"-flags", "+global_header",
|
||||
"-flvflags", "no_duration_filesize",
|
||||
"-f", "flv", youtube_rtmp,
|
||||
]
|
||||
else:
|
||||
ffmpeg_command = [
|
||||
|
||||
source_candidates: list[str] = []
|
||||
_seen_source: set[str] = set()
|
||||
for item in [real_url, *(fallback_urls or [])]:
|
||||
u = (item or "").strip()
|
||||
if u and u not in _seen_source:
|
||||
_seen_source.add(u)
|
||||
source_candidates.append(u)
|
||||
if not source_candidates:
|
||||
source_candidates = [real_url]
|
||||
source_index = 0
|
||||
|
||||
def _emit_relay_heartbeat(state: str, **extra: object) -> None:
|
||||
write_relay_heartbeat(
|
||||
_relay_pm2,
|
||||
{
|
||||
"state": state,
|
||||
"stream_title": stream_title,
|
||||
"source_url": source_candidates[source_index],
|
||||
"codec": codec_v,
|
||||
"record_name": record_name,
|
||||
**extra,
|
||||
},
|
||||
base_dir=_script_dir,
|
||||
)
|
||||
|
||||
def _build_ffmpeg_command(input_url: str) -> list[str]:
|
||||
input_path = os.path.normpath(os.path.expanduser(input_url))
|
||||
input_is_file = os.path.isfile(input_path)
|
||||
if input_is_file:
|
||||
return [
|
||||
ffmpeg_bin, "-y", "-loglevel", "info", "-nostdin",
|
||||
*_stats_args,
|
||||
"-fflags", "+genpts+discardcorrupt",
|
||||
"-err_detect", "ignore_err",
|
||||
"-thread_queue_size", "2048",
|
||||
"-filter_threads", _filter_threads,
|
||||
*_ffmpeg_pre_input,
|
||||
"-re",
|
||||
"-i", input_path,
|
||||
"-vf", _vf_pad,
|
||||
"-c:v", codec_v,
|
||||
*video_args,
|
||||
*_video_mid,
|
||||
"-pix_fmt", _pix_fmt,
|
||||
"-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "2",
|
||||
"-af", _af_chain,
|
||||
"-flags", "+global_header",
|
||||
"-flvflags", "no_duration_filesize",
|
||||
"-f", "flv", youtube_rtmp,
|
||||
]
|
||||
return [
|
||||
ffmpeg_bin, "-y", "-loglevel", "info", "-nostdin",
|
||||
*_stats_args,
|
||||
"-rw_timeout", "50000000",
|
||||
@ -967,8 +1041,7 @@ def start_douyin_youtube_ffplay(
|
||||
*_ffmpeg_pre_input,
|
||||
"-headers", douyin_headers,
|
||||
"-re",
|
||||
"-i", real_url,
|
||||
# bilinear 比 lanczos 轻很多,利于 speed 稳定在 ≥1.0x
|
||||
"-i", input_url,
|
||||
"-vf", _vf_pad,
|
||||
"-c:v", codec_v,
|
||||
*video_args,
|
||||
@ -981,6 +1054,14 @@ def start_douyin_youtube_ffplay(
|
||||
"-f", "flv", youtube_rtmp,
|
||||
]
|
||||
|
||||
print(
|
||||
"[INFO] YouTube Live profile: "
|
||||
f"{'RTMPS' if youtube_rtmp.startswith('rtmps://') else 'RTMP'} | "
|
||||
f"H.264 {codec_v} {video_rate_label} | 720x1280@30 | keyint=2s | AAC 128k/48kHz | real-time input pacing"
|
||||
)
|
||||
ffmpeg_command = _build_ffmpeg_command(source_candidates[source_index])
|
||||
_emit_relay_heartbeat("starting")
|
||||
|
||||
proc = None
|
||||
stderr_q = None
|
||||
reader_t = None
|
||||
@ -1085,6 +1166,13 @@ def start_douyin_youtube_ffplay(
|
||||
|
||||
if is_progress_line:
|
||||
speed = _ffmpeg_speed_value(line_lower)
|
||||
frame, media_time = _ffmpeg_progress_values(line_lower)
|
||||
_emit_relay_heartbeat(
|
||||
"streaming",
|
||||
frame=frame,
|
||||
media_time=media_time,
|
||||
speed=speed,
|
||||
)
|
||||
if speed is not None and time.time() - start_time > START_CHECK_AFTER:
|
||||
if speed > FAST_SPEED_THRESHOLD:
|
||||
fast_speed_strikes += 1
|
||||
@ -1132,6 +1220,16 @@ def start_douyin_youtube_ffplay(
|
||||
break
|
||||
|
||||
except SourceStalled:
|
||||
if source_index + 1 < len(source_candidates):
|
||||
source_index += 1
|
||||
ffmpeg_command = _build_ffmpeg_command(source_candidates[source_index])
|
||||
print(
|
||||
f"[WARN] 切换备用源 URL ({source_index + 1}/{len(source_candidates)}): "
|
||||
f"{source_candidates[source_index][:120]}"
|
||||
)
|
||||
_emit_relay_heartbeat("source_failover", source_index=source_index)
|
||||
retry_delay = INITIAL_RETRY_DELAY
|
||||
continue
|
||||
print(f"[WARN] 当前直播源无进度,返回监控循环刷新源地址 → {record_name}")
|
||||
break
|
||||
|
||||
@ -1146,6 +1244,7 @@ def start_douyin_youtube_ffplay(
|
||||
traceback.print_exc()
|
||||
finally:
|
||||
cleanup_proc(proc)
|
||||
clear_relay_heartbeat(_relay_pm2, base_dir=_script_dir)
|
||||
|
||||
try:
|
||||
recording_time_list.pop(record_name, None)
|
||||
|
||||
@ -7,11 +7,13 @@
|
||||
"dev:api": "python -m uvicorn web:app --host 0.0.0.0 --port 8001 --reload",
|
||||
"dev:console": "python scripts/launch.py --dev",
|
||||
"build": "python scripts/launch.py --build-only",
|
||||
"check": "python -m pytest -q && pnpm -C web-console run check",
|
||||
"start": "python scripts/launch.py",
|
||||
"start:api": "python scripts/launch.py --api-only",
|
||||
"preview": "python scripts/launch.py --skip-build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"concurrently": "^9.1.2"
|
||||
}
|
||||
},
|
||||
"packageManager": "pnpm@10.25.0+sha1.2cfb3ab644446565c127f58165cc76368c9c920b"
|
||||
}
|
||||
|
||||
@ -12,8 +12,14 @@ dependencies = [
|
||||
"pycryptodome>=3.20.0",
|
||||
"distro>=1.9.0",
|
||||
"tqdm>=4.67.1",
|
||||
"httpx[http2]>=0.28.1",
|
||||
"httpx[http2]>=0.28.1,<0.29.0",
|
||||
"PyExecJS>=1.5.1",
|
||||
"fastapi>=0.115.0,<0.116.0",
|
||||
"starlette>=0.40.0,<0.47.0",
|
||||
"pydantic>=2.9.0,<3.0.0",
|
||||
"eval-type-backport>=0.2.0",
|
||||
"uvicorn[standard]>=0.30.0,<0.36.0",
|
||||
"python-multipart>=0.0.9",
|
||||
"PyYAML>=5.4.1"
|
||||
]
|
||||
|
||||
|
||||
@ -175,7 +175,6 @@ def _console_source_paths() -> list[Path]:
|
||||
CONSOLE / "lib",
|
||||
]
|
||||
files = [
|
||||
CONSOLE / "middleware.ts",
|
||||
CONSOLE / "next.config.mjs",
|
||||
CONSOLE / "package.json",
|
||||
CONSOLE / "package-lock.json",
|
||||
|
||||
@ -313,6 +313,10 @@ load_env() {
|
||||
SHELLCRASH_ATTACH_WHEN_DIRECT_OK="${SHELLCRASH_ATTACH_WHEN_DIRECT_OK:-0}"
|
||||
SHELLCRASH_ATTACH_NEKO="${SHELLCRASH_ATTACH_NEKO:-auto}"
|
||||
SHELLCRASH_ATTACH_FFMPEG="${SHELLCRASH_ATTACH_FFMPEG:-auto}"
|
||||
SHELLCRASH_DOCKER_CIDR="${SHELLCRASH_DOCKER_CIDR:-172.16.0.0/12}"
|
||||
ENABLE_NEKO_BROWSER_PROXY="${ENABLE_NEKO_BROWSER_PROXY:-0}"
|
||||
NEKO_SHELLCRASH_PROXY_PORT="${NEKO_SHELLCRASH_PROXY_PORT:-7894}"
|
||||
SHELLCRASH_NEKO_PROXY_NODE="${SHELLCRASH_NEKO_PROXY_NODE:-proxycheap}"
|
||||
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/}"
|
||||
@ -1803,6 +1807,16 @@ neko_browser_proxy_switch_enabled() {
|
||||
esac
|
||||
}
|
||||
|
||||
neko_browser_proxy_manual_enabled() {
|
||||
case "${NEKO_BROWSER_PROXY_MANUAL:-0}" in
|
||||
1|true|TRUE|yes|YES|on|ON|enable|enabled) return 0 ;;
|
||||
esac
|
||||
case "${NEKO_BROWSER_PROXY:-}" in
|
||||
""|0|false|FALSE|off|OFF|none|NONE|direct|DIRECT) return 1 ;;
|
||||
*) return 0 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
shellcrash_config_available() {
|
||||
[ -s "$SHELLCRASH_DIR/yamls/config.yaml" ] || [ -s "/tmp/ShellCrash/config.yaml" ]
|
||||
}
|
||||
@ -1927,7 +1941,7 @@ ensure_shellcrash_docker_transparent_access() {
|
||||
ensure_shellcrash_proxy_ports_for_docker() {
|
||||
ensure_shellcrash_docker_proxy_access "$(shellcrash_mix_port)"
|
||||
ensure_shellcrash_docker_transparent_access
|
||||
if neko_browser_proxy_switch_enabled; then
|
||||
if neko_browser_proxy_switch_enabled || neko_browser_proxy_manual_enabled; then
|
||||
ensure_shellcrash_docker_proxy_access "$(shellcrash_neko_proxy_port)" "Neko ShellCrash proxy from Docker"
|
||||
fi
|
||||
}
|
||||
@ -1949,7 +1963,6 @@ shellcrash_proxy_available() {
|
||||
}
|
||||
|
||||
resolve_neko_browser_proxy() {
|
||||
neko_browser_proxy_switch_enabled || return 0
|
||||
case "${NEKO_BROWSER_PROXY:-}" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
|
||||
printf '%s' "$NEKO_BROWSER_PROXY"
|
||||
@ -1960,6 +1973,7 @@ resolve_neko_browser_proxy() {
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
neko_browser_proxy_switch_enabled || return 0
|
||||
case "${SHELLCRASH_ATTACH_NEKO:-auto}" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
|
||||
return 0
|
||||
|
||||
@ -1168,8 +1168,16 @@ neko_browser_proxy_switch_enabled() {
|
||||
flag_enabled "${ENABLE_NEKO_BROWSER_PROXY:-0}"
|
||||
}
|
||||
|
||||
neko_browser_proxy_manual_enabled() {
|
||||
flag_enabled "${NEKO_BROWSER_PROXY_MANUAL:-0}" && return 0
|
||||
case "${NEKO_BROWSER_PROXY:-}" in
|
||||
""|0|false|FALSE|off|OFF|none|NONE|direct|DIRECT) return 1 ;;
|
||||
*) neko_browser_proxy_url_is_usable "$NEKO_BROWSER_PROXY" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
neko_shellcrash_proxy_enabled() {
|
||||
neko_browser_proxy_switch_enabled || return 1
|
||||
neko_browser_proxy_switch_enabled || neko_browser_proxy_manual_enabled || return 1
|
||||
[ "${ENABLE_NEKO:-1}" = "1" ] || return 1
|
||||
case "$SHELLCRASH_ATTACH_NEKO" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT) return 1 ;;
|
||||
@ -1443,7 +1451,6 @@ shellcrash_proxy_available() {
|
||||
}
|
||||
|
||||
resolve_neko_browser_proxy() {
|
||||
neko_browser_proxy_switch_enabled || return 0
|
||||
case "${NEKO_BROWSER_PROXY:-}" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
|
||||
printf '%s' "$NEKO_BROWSER_PROXY"
|
||||
@ -1456,6 +1463,7 @@ resolve_neko_browser_proxy() {
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
neko_browser_proxy_switch_enabled || return 0
|
||||
case "$SHELLCRASH_ATTACH_NEKO" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
|
||||
return 0
|
||||
|
||||
@ -10,6 +10,7 @@ x-neko-common: &neko-common
|
||||
- "host.docker.internal:host-gateway"
|
||||
|
||||
x-neko-env: &neko-env
|
||||
TZ: "${TZ:-America/Chicago}"
|
||||
DISPLAY: "${NEKO_DISPLAY:-:99.0}"
|
||||
ENV_DISPLAY: "${NEKO_DISPLAY:-:99.0}"
|
||||
ENV_USER: "${NEKO_CONTAINER_USER:-neko}"
|
||||
@ -52,6 +53,7 @@ services:
|
||||
- "${NEKO_WEBRTC_UDPMUX_1}:${NEKO_WEBRTC_UDPMUX_1}/udp"
|
||||
- "${NEKO_WEBRTC_UDP_RANGE_1}:${NEKO_WEBRTC_UDP_RANGE_1}/udp"
|
||||
volumes:
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
- "${NEKO_PROFILE_HOST_DIR_1}:/home/neko/.config/chromium"
|
||||
- "${NEKO_PROFILE_HOST_DIR_1}:/home/neko/.config/google-chrome"
|
||||
- "${NEKO_POLICY_DIR:-./policies}:/etc/chromium/policies/managed:ro"
|
||||
@ -80,6 +82,7 @@ services:
|
||||
- "${NEKO_WEBRTC_UDPMUX_2}:${NEKO_WEBRTC_UDPMUX_2}/udp"
|
||||
- "${NEKO_WEBRTC_UDP_RANGE_2}:${NEKO_WEBRTC_UDP_RANGE_2}/udp"
|
||||
volumes:
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
- "${NEKO_PROFILE_HOST_DIR_2}:/home/neko/.config/chromium"
|
||||
- "${NEKO_PROFILE_HOST_DIR_2}:/home/neko/.config/google-chrome"
|
||||
- "${NEKO_POLICY_DIR:-./policies}:/etc/chromium/policies/managed:ro"
|
||||
@ -108,6 +111,7 @@ services:
|
||||
- "${NEKO_WEBRTC_UDPMUX_3}:${NEKO_WEBRTC_UDPMUX_3}/udp"
|
||||
- "${NEKO_WEBRTC_UDP_RANGE_3}:${NEKO_WEBRTC_UDP_RANGE_3}/udp"
|
||||
volumes:
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
- "${NEKO_PROFILE_HOST_DIR_3}:/home/neko/.config/chromium"
|
||||
- "${NEKO_PROFILE_HOST_DIR_3}:/home/neko/.config/google-chrome"
|
||||
- "${NEKO_POLICY_DIR:-./policies}:/etc/chromium/policies/managed:ro"
|
||||
|
||||
@ -6,10 +6,13 @@ const API_BASES = [
|
||||
];
|
||||
|
||||
async function postTelemetry(payload) {
|
||||
const stored = await chrome.storage.local.get(["liveHubIngestToken"]);
|
||||
const ingestToken = (stored.liveHubIngestToken || "").trim();
|
||||
const body = JSON.stringify({
|
||||
...payload,
|
||||
source: payload.source || "chrome_extension",
|
||||
received_at: Date.now() / 1000,
|
||||
...(ingestToken ? { ingest_token: ingestToken } : {}),
|
||||
});
|
||||
let lastError = "";
|
||||
for (const base of API_BASES) {
|
||||
|
||||
@ -13,6 +13,7 @@ from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from src.android_control import adb_available, list_android_devices
|
||||
from src.control_plane import (
|
||||
CONFIG_DIR,
|
||||
load_hardware_profile,
|
||||
network_iface_stats,
|
||||
query_services,
|
||||
@ -39,7 +40,8 @@ from src.youtube_ini_sync import write_youtube_ini_stream_key
|
||||
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_ingest_auth import verify_ingest_payload
|
||||
from src.youtube_pro_runtime import normalize_youtube_pro_channels, sync_all_youtube_pro_runtime_files
|
||||
from src.youtube_live_store import (
|
||||
close_live_event,
|
||||
get_live_event,
|
||||
@ -484,7 +486,8 @@ async def hub_youtube_pro_channels_write(body: YoutubeProChannelsBody) -> dict[s
|
||||
detail=f"多频道状态数据库写入失败: {exc}; 请确认 config 目录归 live 用户可写",
|
||||
) from exc
|
||||
capacity = await asyncio.to_thread(ensure_neko_capacity_for_youtube_channels, _repo_root, channels)
|
||||
return {"message": "ok", "channels": channels, "neko": capacity}
|
||||
materialize_errors = await asyncio.to_thread(sync_all_youtube_pro_runtime_files, CONFIG_DIR, channels)
|
||||
return {"message": "ok", "channels": channels, "neko": capacity, "materialize_errors": materialize_errors}
|
||||
|
||||
|
||||
@router.get("/youtube/live/summary")
|
||||
@ -526,6 +529,9 @@ async def hub_youtube_live_event_close(event_id: str, body: YoutubeLiveCloseBody
|
||||
|
||||
@router.post("/youtube/live/ingest")
|
||||
async def hub_youtube_live_ingest(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
ok, reason = verify_ingest_payload(payload)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=401, detail=reason)
|
||||
return await asyncio.to_thread(ingest_browser_telemetry, payload)
|
||||
|
||||
|
||||
|
||||
@ -85,7 +85,33 @@ def _restart_timeout_seconds(env_path: Path) -> int:
|
||||
return max(15, min(900, value))
|
||||
|
||||
|
||||
def _restart_neko(root: Path, env_path: Path, log_file: Path) -> tuple[bool, str]:
|
||||
def _render_compose(root: Path, desired: int, log_file: Path) -> tuple[bool, str]:
|
||||
renderer = root / "tools" / "render_neko_compose.py"
|
||||
if not renderer.is_file():
|
||||
return False, "compose_renderer_missing"
|
||||
output = root / "services" / "neko" / "docker-compose.generated.yml"
|
||||
try:
|
||||
with log_file.open("ab") as stream:
|
||||
stamp = datetime.now(timezone.utc).isoformat()
|
||||
stream.write(f"\n[{stamp}] rendering Neko compose count={desired}\n".encode("utf-8"))
|
||||
completed = subprocess.run(
|
||||
["python3", str(renderer), "--count", str(desired), "--output", str(output)],
|
||||
cwd=str(root),
|
||||
stdout=stream,
|
||||
stderr=subprocess.STDOUT,
|
||||
timeout=30,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, "compose_render_timeout"
|
||||
except OSError as exc:
|
||||
return False, f"compose_render_failed: {exc}"
|
||||
if completed.returncode != 0:
|
||||
return False, f"compose_render_exit_{completed.returncode}"
|
||||
return True, ""
|
||||
|
||||
|
||||
def _start_neko(root: Path, env_path: Path, log_file: Path) -> tuple[bool, str]:
|
||||
service_ctl = root / "scripts" / "linux" / "service_ctl.sh"
|
||||
if not service_ctl.is_file():
|
||||
return False, "service_ctl_missing"
|
||||
@ -93,9 +119,9 @@ def _restart_neko(root: Path, env_path: Path, log_file: Path) -> tuple[bool, str
|
||||
try:
|
||||
with log_file.open("ab") as stream:
|
||||
stamp = datetime.now(timezone.utc).isoformat()
|
||||
stream.write(f"\n[{stamp}] ensuring Neko capacity via service_ctl restart\n".encode("utf-8"))
|
||||
stream.write(f"\n[{stamp}] ensuring Neko capacity via service_ctl start\n".encode("utf-8"))
|
||||
completed = subprocess.run(
|
||||
["bash", str(service_ctl), "neko", "restart"],
|
||||
["bash", str(service_ctl), "neko", "start"],
|
||||
cwd=str(root),
|
||||
stdout=stream,
|
||||
stderr=subprocess.STDOUT,
|
||||
@ -103,11 +129,11 @@ def _restart_neko(root: Path, env_path: Path, log_file: Path) -> tuple[bool, str
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, f"restart_timeout_after_{timeout}s"
|
||||
return False, f"start_timeout_after_{timeout}s"
|
||||
except OSError as exc:
|
||||
return False, f"restart_failed: {exc}"
|
||||
return False, f"start_failed: {exc}"
|
||||
if completed.returncode != 0:
|
||||
return False, f"restart_exit_{completed.returncode}"
|
||||
return False, f"start_exit_{completed.returncode}"
|
||||
return True, ""
|
||||
|
||||
|
||||
@ -137,30 +163,52 @@ def ensure_neko_capacity_for_youtube_channels(
|
||||
}
|
||||
|
||||
changed = False
|
||||
log_dir = root / "logs"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_file = log_dir / "neko-capacity.log"
|
||||
if current is None or current < desired:
|
||||
changed = upsert_env_value(env_path, "NEKO_INSTANCE_COUNT", str(desired))
|
||||
restarted = False
|
||||
reason = "compose_missing_desired_service" if current is not None and current >= desired and not compose_ready else ""
|
||||
restart_required = changed or not compose_ready
|
||||
if restart and restart_required:
|
||||
log_dir = root / "logs"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
restarted, restart_reason = _restart_neko(root, env_path, log_dir / "neko-capacity.log")
|
||||
if restart_reason:
|
||||
reason = f"{reason}; {restart_reason}" if reason else restart_reason
|
||||
current_raw = str(desired)
|
||||
current = desired
|
||||
elif not compose_ready:
|
||||
rendered, render_reason = _render_compose(root, desired, log_file)
|
||||
reason = "compose_missing_desired_service"
|
||||
if render_reason:
|
||||
reason = f"{reason}; {render_reason}"
|
||||
compose_ready = _compose_has_neko_service(root, desired)
|
||||
if restarted and not compose_ready:
|
||||
return {
|
||||
"ok": compose_ready,
|
||||
"desired": desired,
|
||||
"current": current,
|
||||
"changed": False,
|
||||
"restart_required": False,
|
||||
"restarted": False,
|
||||
"started": False,
|
||||
"compose_ready": compose_ready,
|
||||
"rendered": rendered,
|
||||
"reason": reason,
|
||||
}
|
||||
started = False
|
||||
reason = "" if changed else "compose_missing_desired_service"
|
||||
restart_required = changed
|
||||
if restart and restart_required:
|
||||
started, start_reason = _start_neko(root, env_path, log_file)
|
||||
if start_reason:
|
||||
reason = f"{reason}; {start_reason}" if reason else start_reason
|
||||
compose_ready = _compose_has_neko_service(root, desired)
|
||||
if started and not compose_ready:
|
||||
suffix = "compose_missing_desired_service_after_restart"
|
||||
reason = f"{reason}; {suffix}" if reason else suffix
|
||||
elif restart_required and not restart:
|
||||
reason = reason or "restart_disabled"
|
||||
return {
|
||||
"ok": not restart_required or (restarted and compose_ready),
|
||||
"ok": not restart_required or (started and compose_ready),
|
||||
"desired": desired,
|
||||
"current": current_raw,
|
||||
"changed": changed,
|
||||
"restart_required": restart_required,
|
||||
"restarted": restarted,
|
||||
"restarted": False,
|
||||
"started": started,
|
||||
"compose_ready": compose_ready,
|
||||
"reason": reason,
|
||||
}
|
||||
|
||||
@ -110,6 +110,124 @@ def automation_recipes() -> list[dict[str, Any]]:
|
||||
]
|
||||
|
||||
|
||||
def ops_playbooks() -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"id": "youtube-live-ready",
|
||||
"title": "YouTube live room ready",
|
||||
"category": "live",
|
||||
"priority": "P0",
|
||||
"description": "Prepare proxy routing, SRS relay, and the Neko browser pool for a YouTube push session.",
|
||||
"services": ["shellcrash", "srs", "neko"],
|
||||
"actions": [
|
||||
{"service": "shellcrash", "action": "restart", "label": "Refresh proxy route engine"},
|
||||
{"service": "srs", "action": "start", "label": "Start RTMP/SRT relay"},
|
||||
{"service": "neko", "action": "start", "label": "Start browser pool"},
|
||||
],
|
||||
"snapshot": True,
|
||||
"status": "ready",
|
||||
},
|
||||
{
|
||||
"id": "tiktok-hdmi-ready",
|
||||
"title": "TikTok HDMI ingest ready",
|
||||
"category": "live",
|
||||
"priority": "P0",
|
||||
"description": "Bring up the media relay and audio bridge used by HDMI capture and TikTok replay flows.",
|
||||
"services": ["srs", "pulseaudio"],
|
||||
"actions": [
|
||||
{"service": "srs", "action": "start", "label": "Start relay for HDMI output"},
|
||||
{"service": "pulseaudio", "action": "start", "label": "Start audio bridge"},
|
||||
],
|
||||
"snapshot": True,
|
||||
"status": "ready",
|
||||
},
|
||||
{
|
||||
"id": "remote-browser-ready",
|
||||
"title": "Remote browser access ready",
|
||||
"category": "remote",
|
||||
"priority": "P0",
|
||||
"description": "Prepare TURN relay, proxy routing, and Neko for remote WebRTC access.",
|
||||
"services": ["coturn", "shellcrash", "neko"],
|
||||
"actions": [
|
||||
{"service": "coturn", "action": "start", "label": "Start TURN relay"},
|
||||
{"service": "shellcrash", "action": "restart", "label": "Refresh proxy route engine"},
|
||||
{"service": "neko", "action": "restart", "label": "Restart browser pool"},
|
||||
],
|
||||
"snapshot": True,
|
||||
"status": "ready",
|
||||
},
|
||||
{
|
||||
"id": "studio-alerts-ready",
|
||||
"title": "Studio alerts ready",
|
||||
"category": "studio",
|
||||
"priority": "P1",
|
||||
"description": "Start local notification and Wake-on-LAN support before unattended operation.",
|
||||
"services": ["ntfy", "wol"],
|
||||
"actions": [
|
||||
{"service": "ntfy", "action": "start", "label": "Start notification server"},
|
||||
{"service": "wol", "action": "status", "label": "Verify Wake-on-LAN controller"},
|
||||
],
|
||||
"snapshot": True,
|
||||
"status": "ready",
|
||||
},
|
||||
{
|
||||
"id": "android-capture-ready",
|
||||
"title": "Android capture ready",
|
||||
"category": "android",
|
||||
"priority": "P1",
|
||||
"description": "Bring Android container, ADB, and browser control services online for mobile capture workflows.",
|
||||
"services": ["redroid", "adb", "android_panel"],
|
||||
"actions": [
|
||||
{"service": "redroid", "action": "start", "label": "Start Android container"},
|
||||
{"service": "adb", "action": "start", "label": "Start ADB bridge"},
|
||||
{"service": "android_panel", "action": "start", "label": "Start browser Android control"},
|
||||
],
|
||||
"snapshot": True,
|
||||
"status": "ready",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def get_ops_playbook(playbook_id: str) -> dict[str, Any]:
|
||||
normalized = (playbook_id or "").strip()
|
||||
for playbook in ops_playbooks():
|
||||
if playbook.get("id") == normalized:
|
||||
return playbook
|
||||
raise KeyError(f"Unknown playbook: {playbook_id}")
|
||||
|
||||
|
||||
def ops_playbooks_with_service_state(services: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
by_id = {str(item.get("service_id")): item for item in services}
|
||||
rows: list[dict[str, Any]] = []
|
||||
for playbook in ops_playbooks():
|
||||
service_ids = [str(item) for item in playbook.get("services", [])]
|
||||
dependencies: list[dict[str, Any]] = []
|
||||
for service_id in service_ids:
|
||||
service = by_id.get(service_id, {})
|
||||
dependencies.append(
|
||||
{
|
||||
"service_id": service_id,
|
||||
"label": service.get("label") or service_id,
|
||||
"available": bool(service.get("available")),
|
||||
"running": bool(service.get("running")),
|
||||
"status": service.get("status") or "unknown",
|
||||
"detail": service.get("detail") or "",
|
||||
}
|
||||
)
|
||||
required = len(dependencies)
|
||||
running = sum(1 for item in dependencies if item["running"])
|
||||
available = sum(1 for item in dependencies if item["available"])
|
||||
row = dict(playbook)
|
||||
row["dependencies"] = dependencies
|
||||
row["required_count"] = required
|
||||
row["running_count"] = running
|
||||
row["available_count"] = available
|
||||
row["ready"] = required > 0 and running == required
|
||||
row["status"] = "ready" if row["ready"] else "partial" if running else playbook.get("status", "ready")
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def app_blueprints(installed_ids: set[str] | None = None) -> list[dict[str, Any]]:
|
||||
installed = installed_ids or set()
|
||||
rows = [
|
||||
@ -320,6 +438,7 @@ def studio_ops_summary(
|
||||
return {
|
||||
"doctor": system_doctor(services, deployment),
|
||||
"inventory": device_inventory(base_dir, refresh=refresh),
|
||||
"playbooks": ops_playbooks_with_service_state(services),
|
||||
"recipes": automation_recipes(),
|
||||
"apps": app_blueprints(installed),
|
||||
"backups": {"snapshots": list_system_snapshots(base_dir)},
|
||||
|
||||
@ -73,6 +73,21 @@ def _looks_like_ffmpeg_progress(tail: str) -> bool:
|
||||
return "frame=" in tail and "time=" in tail and _has_any(tail, ("bitrate=", "speed="))
|
||||
|
||||
|
||||
def _looks_like_ffmpeg_starting(tail: str) -> bool:
|
||||
return _has_any(
|
||||
tail,
|
||||
(
|
||||
"starting ffmpeg",
|
||||
"ffmpeg command",
|
||||
"opening input",
|
||||
"opening output",
|
||||
"rtmps://a.rtmps.youtube.com/live2/",
|
||||
"rtmp://a.rtmp.youtube.com/live2/",
|
||||
"youtube.com/live2/",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _ffmpeg_progress_samples(tail: str) -> list[dict[str, float | int]]:
|
||||
samples: list[dict[str, float | int]] = []
|
||||
for match in _FFMPEG_PROGRESS_RE.finditer(tail or ""):
|
||||
@ -136,11 +151,11 @@ 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
|
||||
)
|
||||
log_recent = log_age_seconds is None or log_age_seconds <= 20
|
||||
has_recent_ffmpeg_progress = _looks_like_ffmpeg_progress(tail) and log_recent
|
||||
has_ffmpeg_worker = bool(pids)
|
||||
|
||||
if family == "youtube" and not pids and not has_recent_ffmpeg_progress and _looks_like_youtube_key_rejected(tail):
|
||||
if family == "youtube" 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, "
|
||||
@ -150,15 +165,18 @@ def summarize_process_activity(
|
||||
if _has_any(tail, ("请在 ", "配置 key", "stream_key", "key=你的stream_key")):
|
||||
business_status = "misconfigured"
|
||||
business_note = "YouTube stream key is missing or invalid"
|
||||
elif family == "youtube" and pids and progress_stalled:
|
||||
elif family == "youtube" and has_recent_ffmpeg_progress and has_ffmpeg_worker and progress_stalled:
|
||||
business_status = "source_stalled"
|
||||
business_note = "FFmpeg is running, but frame/time progress is stalled"
|
||||
elif family == "youtube" and pids and speed_low:
|
||||
elif family == "youtube" and has_recent_ffmpeg_progress and has_ffmpeg_worker and speed_low:
|
||||
business_status = "relay_slow"
|
||||
business_note = "FFmpeg is running, but recent relay speed is below realtime"
|
||||
elif pids or has_recent_ffmpeg_progress:
|
||||
elif has_recent_ffmpeg_progress:
|
||||
business_status = "streaming"
|
||||
business_note = "FFmpeg relay worker is running" if pids else "FFmpeg relay is emitting video frames"
|
||||
business_note = "FFmpeg relay is emitting video frames"
|
||||
elif family == "youtube" and has_ffmpeg_worker and _looks_like_ffmpeg_starting(tail) and log_recent:
|
||||
business_status = "relay_starting"
|
||||
business_note = "FFmpeg worker is present, but no video progress has been observed yet"
|
||||
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"
|
||||
@ -200,5 +218,5 @@ def summarize_process_activity(
|
||||
"ffmpeg_progress_stalled": progress_stalled,
|
||||
"ffmpeg_speed_low": speed_low,
|
||||
"is_pushing": business_status in {"streaming", "relay_slow"}
|
||||
or (business_status == "source_stalled" and bool(pids)),
|
||||
or (business_status == "source_stalled" and has_recent_ffmpeg_progress and has_ffmpeg_worker),
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ import re
|
||||
from pathlib import Path
|
||||
|
||||
_SAFE_PM2_SEGMENT = re.compile(r"[^a-zA-Z0-9_.-]+")
|
||||
_YOUTUBE_PRO_PM2_PREFIX = "youtube2__"
|
||||
|
||||
|
||||
def sanitize_pm2_segment(value: str) -> str:
|
||||
@ -15,6 +16,21 @@ def is_youtube_like_pm2(pm2: str | None) -> bool:
|
||||
return low.startswith("youtube") or low.startswith("douyin_youtube")
|
||||
|
||||
|
||||
def is_youtube_pro_pm2(pm2: str | None) -> bool:
|
||||
return (pm2 or "").strip().lower().startswith(_YOUTUBE_PRO_PM2_PREFIX)
|
||||
|
||||
|
||||
def is_managed_youtube_pm2(pm2: str | None) -> bool:
|
||||
"""PM2 names that must use per-process managed ini pair (never legacy cross-lane fallback)."""
|
||||
low = (pm2 or "").strip().lower()
|
||||
if not is_youtube_like_pm2(pm2):
|
||||
return False
|
||||
if is_youtube_pro_pm2(pm2):
|
||||
return True
|
||||
safe = sanitize_pm2_segment(pm2 or "")
|
||||
return bool(safe and safe != "youtube")
|
||||
|
||||
|
||||
def resolve_youtube_style_config_paths(base_dir: str | Path, pm2: str | None = None) -> tuple[str, str]:
|
||||
root = Path(base_dir)
|
||||
legacy_youtube = root / "config" / "youtube.ini"
|
||||
@ -27,6 +43,9 @@ def resolve_youtube_style_config_paths(base_dir: str | Path, pm2: str | None = N
|
||||
managed_youtube = root / "config" / f"youtube.{safe}.ini"
|
||||
managed_url = root / "config" / f"URL_config.{safe}.ini"
|
||||
|
||||
if is_managed_youtube_pm2(pm2):
|
||||
return str(managed_youtube), str(managed_url)
|
||||
|
||||
managed_youtube_exists = managed_youtube.is_file()
|
||||
managed_url_exists = managed_url.is_file()
|
||||
legacy_youtube_exists = legacy_youtube.is_file()
|
||||
|
||||
64
d2ypp2/src/youtube_encoder_cache.py
Normal file
64
d2ypp2/src/youtube_encoder_cache.py
Normal file
@ -0,0 +1,64 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
_CACHE_TTL_SECONDS = max(3600, int(os.environ.get("YOUTUBE_ENCODER_CACHE_TTL", str(24 * 3600))))
|
||||
|
||||
|
||||
def _cache_path(base_dir: str | Path | None = None) -> Path:
|
||||
root = Path(base_dir or os.environ.get("LIVE_PROJECT_ROOT") or Path(__file__).resolve().parent.parent)
|
||||
path = root / "runtime"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path / "encoder_cache.json"
|
||||
|
||||
|
||||
def load_encoder_cache(base_dir: str | Path | None = None) -> dict[str, Any]:
|
||||
path = _cache_path(base_dir)
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def get_cached_encoder(
|
||||
machine: str,
|
||||
ffmpeg_bin: str,
|
||||
*,
|
||||
base_dir: str | Path | None = None,
|
||||
) -> str | None:
|
||||
blob = load_encoder_cache(base_dir)
|
||||
key = f"{machine}|{ffmpeg_bin}"
|
||||
row = blob.get(key)
|
||||
if not isinstance(row, dict):
|
||||
return None
|
||||
if time.time() - float(row.get("ts") or 0) > _CACHE_TTL_SECONDS:
|
||||
return None
|
||||
name = str(row.get("encoder") or "").strip()
|
||||
return name or None
|
||||
|
||||
|
||||
def store_cached_encoder(
|
||||
machine: str,
|
||||
ffmpeg_bin: str,
|
||||
encoder: str,
|
||||
*,
|
||||
base_dir: str | Path | None = None,
|
||||
) -> None:
|
||||
if not encoder:
|
||||
return
|
||||
path = _cache_path(base_dir)
|
||||
blob = load_encoder_cache(base_dir)
|
||||
key = f"{machine}|{ffmpeg_bin}"
|
||||
blob[key] = {"encoder": encoder, "ts": time.time()}
|
||||
try:
|
||||
path.write_text(json.dumps(blob, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
50
d2ypp2/src/youtube_ingest_auth.py
Normal file
50
d2ypp2/src/youtube_ingest_auth.py
Normal file
@ -0,0 +1,50 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
|
||||
def ingest_token() -> str:
|
||||
return (
|
||||
os.environ.get("YOUTUBE_INGEST_TOKEN")
|
||||
or os.environ.get("LIVE_YOUTUBE_INGEST_TOKEN")
|
||||
or ""
|
||||
).strip()
|
||||
|
||||
|
||||
def ingest_auth_required() -> bool:
|
||||
raw = (os.environ.get("YOUTUBE_INGEST_REQUIRE_AUTH") or os.environ.get("LIVE_YOUTUBE_INGEST_REQUIRE_AUTH") or "1").strip().lower()
|
||||
if raw in {"0", "false", "no", "off"}:
|
||||
return False
|
||||
return bool(ingest_token())
|
||||
|
||||
|
||||
def verify_ingest_payload(payload: dict[str, Any]) -> tuple[bool, str]:
|
||||
if not ingest_auth_required():
|
||||
return True, ""
|
||||
token = ingest_token()
|
||||
if not token:
|
||||
return False, "ingest auth enabled but YOUTUBE_INGEST_TOKEN is empty"
|
||||
|
||||
provided = str(payload.get("ingest_token") or payload.get("token") or "").strip()
|
||||
if provided and hmac.compare_digest(provided, token):
|
||||
return True, ""
|
||||
|
||||
ts_raw = payload.get("ingest_ts") or payload.get("ts")
|
||||
sig = str(payload.get("ingest_sig") or payload.get("sig") or "").strip()
|
||||
if sig and ts_raw is not None:
|
||||
try:
|
||||
ts = int(float(ts_raw))
|
||||
except (TypeError, ValueError):
|
||||
return False, "invalid ingest timestamp"
|
||||
if abs(time.time() - ts) > 900:
|
||||
return False, "ingest signature expired"
|
||||
body = f"{ts}|{payload.get('process') or payload.get('lane') or 'chrome_extension'}"
|
||||
expected = hmac.new(token.encode("utf-8"), body.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
if hmac.compare_digest(sig, expected):
|
||||
return True, ""
|
||||
|
||||
return False, "invalid or missing ingest credentials"
|
||||
@ -45,6 +45,12 @@ def _connect(db_path: Path | None = None) -> sqlite3.Connection:
|
||||
conn = sqlite3.connect(str(path), timeout=12)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA busy_timeout=12000")
|
||||
conn.execute("PRAGMA foreign_keys=ON")
|
||||
conn.execute("PRAGMA synchronous=NORMAL")
|
||||
try:
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS youtube_live_events (
|
||||
@ -443,11 +449,11 @@ def _primary_popup(payload: dict[str, Any]) -> str:
|
||||
|
||||
|
||||
def _payload_indicates_process_inactive(payload: dict[str, Any]) -> bool:
|
||||
if bool(payload.get("is_pushing")) or bool(payload.get("ffmpeg_active")):
|
||||
business_status = str(payload.get("business_status") or "").strip().lower()
|
||||
if bool(payload.get("is_pushing")) or business_status in {"streaming", "relay_slow", "source_stalled"}:
|
||||
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")
|
||||
@ -465,12 +471,32 @@ def _payload_indicates_process_inactive(payload: dict[str, Any]) -> bool:
|
||||
"stopped",
|
||||
"unknown",
|
||||
}
|
||||
stopped_business = {"configured", "idle", "not_running", "ready", "stopped", "unknown"}
|
||||
active_business = {
|
||||
"relay_starting",
|
||||
"source_live",
|
||||
"monitoring",
|
||||
}
|
||||
if business_status in active_business and process_status in {"online", "running", "launching"}:
|
||||
return False
|
||||
|
||||
stopped_business = {
|
||||
"configured",
|
||||
"idle",
|
||||
"inactive",
|
||||
"misconfigured",
|
||||
"not_running",
|
||||
"ready",
|
||||
"stale",
|
||||
"stopped",
|
||||
"unknown",
|
||||
"waiting_source",
|
||||
"youtube_key_rejected",
|
||||
}
|
||||
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(
|
||||
if payload.get("is_pushing") is False and any(
|
||||
token in raw
|
||||
for token in (
|
||||
"not running",
|
||||
|
||||
@ -279,3 +279,22 @@ def validate_youtube_runtime_files(
|
||||
if not _has_noncomment_url(url_text):
|
||||
fallback_errors.append(f"{process}: source URL missing")
|
||||
return fallback_errors
|
||||
|
||||
|
||||
def sync_all_youtube_pro_runtime_files(
|
||||
config_dir: Path,
|
||||
channels: Iterable[dict[str, Any]],
|
||||
) -> list[str]:
|
||||
"""Materialize Hub KV channel drafts to managed ini files for every Pro lane."""
|
||||
errors: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for channel in channels:
|
||||
if not isinstance(channel, dict):
|
||||
continue
|
||||
pm2 = channel_pm2_name(channel)
|
||||
if not pm2 or pm2 in seen:
|
||||
continue
|
||||
seen.add(pm2)
|
||||
_, row_errors = ensure_youtube_pro_channel_runtime_files(config_dir, pm2, channels)
|
||||
errors.extend(row_errors)
|
||||
return errors
|
||||
|
||||
@ -164,7 +164,12 @@ def build_youtube_quality_guard_report(
|
||||
|
||||
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 ""))
|
||||
pushing = bool(row.get("is_pushing"))
|
||||
metrics = (
|
||||
parse_ffmpeg_metrics(str(row.get("recent_log") or ""), str(row.get("recent_error") or ""))
|
||||
if pushing
|
||||
else parse_ffmpeg_metrics("")
|
||||
)
|
||||
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 ""))
|
||||
@ -199,7 +204,7 @@ def build_youtube_quality_guard_report(
|
||||
"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")),
|
||||
"is_pushing": pushing,
|
||||
"ffmpeg_active": bool(row.get("ffmpeg_active")),
|
||||
"score": score,
|
||||
"metrics": metrics,
|
||||
@ -210,10 +215,11 @@ def build_youtube_quality_guard_report(
|
||||
}
|
||||
)
|
||||
|
||||
active_events = int(((live_summary.get("stats") or {}).get("active_events") or len(live_summary.get("active") or [])) or 0)
|
||||
raw_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"])
|
||||
active_events = raw_active_events
|
||||
score = int(sum(lane["score"] for lane in lanes) / len(lanes)) if lanes else 0
|
||||
|
||||
if pushing_count == 0:
|
||||
|
||||
56
d2ypp2/src/youtube_relay_heartbeat.py
Normal file
56
d2ypp2/src/youtube_relay_heartbeat.py
Normal file
@ -0,0 +1,56 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _runtime_dir(base_dir: str | Path | None = None) -> Path:
|
||||
root = Path(base_dir or os.environ.get("LIVE_PROJECT_ROOT") or Path(__file__).resolve().parent.parent)
|
||||
path = root / "runtime" / "youtube_relay"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def heartbeat_path(pm2: str, *, base_dir: str | Path | None = None) -> Path:
|
||||
safe = "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in (pm2 or "youtube").strip()) or "youtube"
|
||||
return _runtime_dir(base_dir) / f"{safe}.json"
|
||||
|
||||
|
||||
def write_relay_heartbeat(
|
||||
pm2: str,
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
base_dir: str | Path | None = None,
|
||||
) -> None:
|
||||
data = dict(payload)
|
||||
data["updated_at"] = time.time()
|
||||
data["pm2"] = (pm2 or "").strip() or "youtube"
|
||||
path = heartbeat_path(data["pm2"], base_dir=base_dir)
|
||||
tmp = path.with_suffix(".json.tmp")
|
||||
try:
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
||||
tmp.replace(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def read_relay_heartbeat(pm2: str, *, base_dir: str | Path | None = None) -> dict[str, Any]:
|
||||
path = heartbeat_path(pm2, base_dir=base_dir)
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return {}
|
||||
|
||||
|
||||
def clear_relay_heartbeat(pm2: str, *, base_dir: str | Path | None = None) -> None:
|
||||
path = heartbeat_path(pm2, base_dir=base_dir)
|
||||
try:
|
||||
if path.is_file():
|
||||
path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
15
d2ypp2/src/youtube_relay_supervisor.py
Normal file
15
d2ypp2/src/youtube_relay_supervisor.py
Normal file
@ -0,0 +1,15 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""YouTube relay supervisor helpers.
|
||||
|
||||
The relay worker remains `douyin_youtube_ffplay.start_douyin_youtube_ffplay`.
|
||||
This module exposes structured runtime state for the control plane.
|
||||
"""
|
||||
|
||||
from src.youtube_relay_heartbeat import clear_relay_heartbeat, read_relay_heartbeat, write_relay_heartbeat
|
||||
|
||||
__all__ = [
|
||||
"clear_relay_heartbeat",
|
||||
"read_relay_heartbeat",
|
||||
"write_relay_heartbeat",
|
||||
]
|
||||
@ -349,6 +349,10 @@ rules:
|
||||
self.assertIn("system_direct_global_ready()", common)
|
||||
self.assertIn("shellcrash_should_autostart_on_direct_fail()", common)
|
||||
self.assertIn("SHELLCRASH_AUTOSTART", common)
|
||||
self.assertIn("SHELLCRASH_DOCKER_CIDR", common)
|
||||
self.assertIn("ENABLE_NEKO_BROWSER_PROXY", common)
|
||||
self.assertIn("NEKO_SHELLCRASH_PROXY_PORT", common)
|
||||
self.assertIn("SHELLCRASH_NEKO_PROXY_NODE", common)
|
||||
self.assertIn("service_homeassistant_start()", script)
|
||||
self.assertIn("service_frigate_start()", script)
|
||||
self.assertIn("service_frigate_auto()", script)
|
||||
|
||||
@ -79,6 +79,12 @@ class LaunchConsoleBuildTests(unittest.TestCase):
|
||||
with patch.object(self.launch, "CONSOLE", console):
|
||||
self.assertFalse(self.launch._console_deps_need_refresh())
|
||||
|
||||
def test_console_source_paths_do_not_require_removed_middleware(self) -> None:
|
||||
paths = [path.name for path in self.launch._console_source_paths()]
|
||||
|
||||
self.assertIn("next.config.mjs", paths)
|
||||
self.assertNotIn("middleware.ts", paths)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
45
d2ypp2/tests/test_live_console_status_ui.py
Normal file
45
d2ypp2/tests/test_live_console_status_ui.py
Normal file
@ -0,0 +1,45 @@
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_live_log_card_does_not_treat_process_online_as_pushing() -> None:
|
||||
source = Path("web-console/components/live-product/LiveProcessLiveLogCard.tsx").read_text(encoding="utf-8")
|
||||
|
||||
assert "const onlineNow" not in source
|
||||
assert "live: pushingNow || onlineNow" not in source
|
||||
assert "!!monitorRow?.is_pushing" not in source
|
||||
assert "pushingNow || monitorRow?.ffmpeg_active" not in source
|
||||
assert "live: pushingNow," in source
|
||||
|
||||
|
||||
def test_youtube_pro_lane_metrics_do_not_treat_process_online_as_live() -> None:
|
||||
source = Path("web-console/components/live-product/LiveYoutubeUnmannedView.tsx").read_text(encoding="utf-8")
|
||||
|
||||
assert "live: laneLiveMetrics.live || rowOnline || isLivePushingRow(row)" not in source
|
||||
assert "live: laneLiveMetrics.live || isLivePushingRow(row)" in source
|
||||
assert '(business === "source_stalled" && !!row?.ffmpeg_active)' not in source
|
||||
assert 'if (pm2StatusOnline(row?.process_status)) return "bg-zinc-500/15 text-zinc-200 ring-zinc-500/25";' in source
|
||||
|
||||
|
||||
def test_ffmpeg_metrics_live_flag_only_uses_is_pushing() -> None:
|
||||
source = Path("web-console/lib/ffmpegMetrics.ts").read_text(encoding="utf-8")
|
||||
|
||||
assert "const live = !!(row?.is_pushing || row?.ffmpeg_active);" not in source
|
||||
assert "const live = !!row?.is_pushing;" in source
|
||||
|
||||
|
||||
def test_youtube_advanced_panels_hidden_by_default() -> None:
|
||||
source = Path("web-console/components/live-product/LiveYoutubeUnmannedView.tsx").read_text(encoding="utf-8")
|
||||
|
||||
assert "const HIDE_YOUTUBE_RELAY_SNAPSHOT = true;" in source
|
||||
assert "const HIDE_YOUTUBE_QUALITY_GUARD = true;" in source
|
||||
assert "const HIDE_YOUTUBE_LIVE_EVENT_HUB = true;" in source
|
||||
assert "{!HIDE_YOUTUBE_QUALITY_GUARD ? qualityGuardPanel : null}" in source
|
||||
|
||||
|
||||
def test_host04_patch_keeps_neko_proxy_separate_from_push_node() -> None:
|
||||
source = Path("tools/remote_patch_host04.py").read_text(encoding="utf-8")
|
||||
|
||||
assert 'SHELLCRASH_PUSH_NODE = "1d2da142-singbox_tuic5"' in source
|
||||
assert 'NEKO_PROXY_NODE = "proxycheap"' in source
|
||||
assert '"SHELLCRASH_NEKO_PROXY_NODE": NEKO_PROXY_NODE' in source
|
||||
assert 'data=json.dumps({"name": SHELLCRASH_PUSH_NODE}).encode()' in source
|
||||
@ -37,7 +37,7 @@ class NekoCapacityTests(unittest.TestCase):
|
||||
self.assertTrue(changed)
|
||||
self.assertEqual(env.read_text(encoding="utf-8"), "HOSTNAME_ALIAS=live\nNEKO_INSTANCE_COUNT=3\nPORT=8001\n")
|
||||
|
||||
def test_ensure_capacity_increases_env_and_restarts_neko_synchronously(self) -> None:
|
||||
def test_ensure_capacity_increases_env_and_starts_missing_neko_instances(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
env = root / "config" / "system-stack.env"
|
||||
@ -60,13 +60,14 @@ class NekoCapacityTests(unittest.TestCase):
|
||||
self.assertTrue(result["ok"])
|
||||
self.assertTrue(result["changed"])
|
||||
self.assertTrue(result["restart_required"])
|
||||
self.assertTrue(result["restarted"])
|
||||
self.assertFalse(result["restarted"])
|
||||
self.assertTrue(result["started"])
|
||||
self.assertTrue(result["compose_ready"])
|
||||
self.assertIn("NEKO_INSTANCE_COUNT=3", env.read_text(encoding="utf-8"))
|
||||
run.assert_called_once()
|
||||
self.assertEqual(run.call_args.args[0][-2:], ["neko", "restart"])
|
||||
self.assertEqual(run.call_args.args[0][-2:], ["neko", "start"])
|
||||
|
||||
def test_ensure_capacity_repairs_stale_generated_compose_even_when_env_count_is_high_enough(self) -> None:
|
||||
def test_ensure_capacity_repairs_stale_generated_compose_without_restarting_when_env_count_is_high_enough(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
env = root / "config" / "system-stack.env"
|
||||
@ -75,6 +76,9 @@ class NekoCapacityTests(unittest.TestCase):
|
||||
service_ctl = root / "scripts" / "linux" / "service_ctl.sh"
|
||||
service_ctl.parent.mkdir(parents=True)
|
||||
service_ctl.write_text("#!/usr/bin/env bash\n", encoding="utf-8")
|
||||
renderer = root / "tools" / "render_neko_compose.py"
|
||||
renderer.parent.mkdir(parents=True)
|
||||
renderer.write_text("#!/usr/bin/env python3\n", encoding="utf-8")
|
||||
|
||||
with patch("src.neko_capacity._compose_has_neko_service", side_effect=[False, True]):
|
||||
with patch(
|
||||
@ -88,10 +92,12 @@ class NekoCapacityTests(unittest.TestCase):
|
||||
|
||||
self.assertTrue(result["ok"])
|
||||
self.assertFalse(result["changed"])
|
||||
self.assertTrue(result["restart_required"])
|
||||
self.assertTrue(result["restarted"])
|
||||
self.assertFalse(result["restart_required"])
|
||||
self.assertFalse(result["restarted"])
|
||||
self.assertTrue(result["rendered"])
|
||||
self.assertIn("compose_missing_desired_service", result["reason"])
|
||||
run.assert_called_once()
|
||||
self.assertIn("render_neko_compose.py", str(run.call_args.args[0]))
|
||||
|
||||
def test_ensure_capacity_reports_restart_success_but_missing_compose_as_not_ok(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
@ -114,10 +120,30 @@ class NekoCapacityTests(unittest.TestCase):
|
||||
)
|
||||
|
||||
self.assertFalse(result["ok"])
|
||||
self.assertTrue(result["restarted"])
|
||||
self.assertFalse(result["restarted"])
|
||||
self.assertTrue(result["started"])
|
||||
self.assertFalse(result["compose_ready"])
|
||||
self.assertIn("compose_missing_desired_service_after_restart", result["reason"])
|
||||
|
||||
def test_ensure_capacity_reports_compose_render_failure_without_restart_when_count_is_high_enough(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
env = root / "config" / "system-stack.env"
|
||||
env.parent.mkdir()
|
||||
env.write_text("NEKO_INSTANCE_COUNT=2\n", encoding="utf-8")
|
||||
|
||||
with patch("src.neko_capacity._compose_has_neko_service", return_value=False):
|
||||
result = ensure_neko_capacity_for_youtube_channels(
|
||||
root,
|
||||
[{"id": "lane1"}, {"id": "lane2"}],
|
||||
)
|
||||
|
||||
self.assertFalse(result["ok"])
|
||||
self.assertFalse(result["restart_required"])
|
||||
self.assertFalse(result["restarted"])
|
||||
self.assertFalse(result["compose_ready"])
|
||||
self.assertIn("compose_renderer_missing", result["reason"])
|
||||
|
||||
def test_ensure_capacity_keeps_saved_env_when_restart_spawn_fails(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
@ -137,11 +163,12 @@ class NekoCapacityTests(unittest.TestCase):
|
||||
|
||||
self.assertTrue(result["changed"])
|
||||
self.assertFalse(result["restarted"])
|
||||
self.assertFalse(result["started"])
|
||||
self.assertFalse(result["ok"])
|
||||
self.assertIn("restart_failed", result["reason"])
|
||||
self.assertIn("start_failed", result["reason"])
|
||||
self.assertIn("NEKO_INSTANCE_COUNT=3", env.read_text(encoding="utf-8"))
|
||||
|
||||
def test_ensure_capacity_keeps_saved_env_when_restart_exits_nonzero(self) -> None:
|
||||
def test_ensure_capacity_keeps_saved_env_when_start_exits_nonzero(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
env = root / "config" / "system-stack.env"
|
||||
@ -163,8 +190,9 @@ class NekoCapacityTests(unittest.TestCase):
|
||||
|
||||
self.assertTrue(result["changed"])
|
||||
self.assertFalse(result["restarted"])
|
||||
self.assertFalse(result["started"])
|
||||
self.assertFalse(result["ok"])
|
||||
self.assertIn("restart_exit_17", result["reason"])
|
||||
self.assertIn("start_exit_17", result["reason"])
|
||||
self.assertIn("NEKO_INSTANCE_COUNT=3", env.read_text(encoding="utf-8"))
|
||||
|
||||
def test_ensure_capacity_does_not_downscale_manual_larger_count(self) -> None:
|
||||
|
||||
@ -178,6 +178,18 @@ class NekoConfigTests(unittest.TestCase):
|
||||
with patch.dict(os.environ, {"NEKO_DOCKER_HOST_IP": "172.18.0.1"}, clear=False):
|
||||
routed = module.render(2)
|
||||
self.assertEqual(routed.count('"host.docker.internal:172.18.0.1"'), 2)
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"ENABLE_NEKO_BROWSER_PROXY": "1",
|
||||
"NEKO_BROWSER_PROXY": "",
|
||||
"NEKO_DOCKER_HOST_IP": "172.18.0.1",
|
||||
"NEKO_SHELLCRASH_PROXY_PORT": "7894",
|
||||
},
|
||||
clear=False,
|
||||
):
|
||||
auto_proxy_rendered = module.render(2)
|
||||
self.assertIn('NEKO_BROWSER_PROXY: "http://172.18.0.1:7894"', auto_proxy_rendered)
|
||||
self.assertEqual(rendered.count("apparmor:unconfined"), 4)
|
||||
self.assertIn('NEKO_MANAGED_POLICIES: "1"', rendered)
|
||||
self.assertIn('NEKO_TAMPERMONKEY_REPAIR: "1"', rendered)
|
||||
|
||||
@ -6,7 +6,15 @@ 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
|
||||
from src.ops_center import (
|
||||
app_blueprints,
|
||||
create_system_snapshot,
|
||||
get_ops_playbook,
|
||||
ops_playbooks,
|
||||
ops_playbooks_with_service_state,
|
||||
studio_ops_summary,
|
||||
system_doctor,
|
||||
)
|
||||
|
||||
|
||||
class OpsCenterTests(unittest.TestCase):
|
||||
@ -28,6 +36,34 @@ class OpsCenterTests(unittest.TestCase):
|
||||
self.assertTrue(by_id["coturn"]["installed"])
|
||||
self.assertFalse(by_id["freshrss"]["installed"])
|
||||
|
||||
def test_ops_playbooks_define_executable_service_actions(self) -> None:
|
||||
rows = ops_playbooks()
|
||||
by_id = {item["id"]: item for item in rows}
|
||||
|
||||
self.assertIn("youtube-live-ready", by_id)
|
||||
youtube = get_ops_playbook("youtube-live-ready")
|
||||
self.assertIn("shellcrash", youtube["services"])
|
||||
self.assertIn("srs", youtube["services"])
|
||||
self.assertIn("neko", youtube["services"])
|
||||
self.assertTrue(youtube["snapshot"])
|
||||
self.assertTrue(all(step.get("service") and step.get("action") for step in youtube["actions"]))
|
||||
|
||||
def test_ops_playbooks_include_dependency_runtime_state(self) -> None:
|
||||
rows = ops_playbooks_with_service_state(
|
||||
[
|
||||
{"service_id": "shellcrash", "available": True, "running": True, "status": "online"},
|
||||
{"service_id": "srs", "available": True, "running": False, "status": "stopped"},
|
||||
{"service_id": "neko", "available": False, "running": False, "status": "unavailable"},
|
||||
]
|
||||
)
|
||||
youtube = next(item for item in rows if item["id"] == "youtube-live-ready")
|
||||
|
||||
self.assertEqual(youtube["required_count"], 3)
|
||||
self.assertEqual(youtube["running_count"], 1)
|
||||
self.assertEqual(youtube["available_count"], 2)
|
||||
self.assertFalse(youtube["ready"])
|
||||
self.assertEqual(youtube["status"], "partial")
|
||||
|
||||
def test_create_system_snapshot_includes_managed_configs(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
@ -54,6 +90,7 @@ class OpsCenterTests(unittest.TestCase):
|
||||
self.assertIn("doctor", summary)
|
||||
self.assertEqual(summary["inventory"]["counts"]["serial"], 1)
|
||||
self.assertEqual(summary["inventory"]["counts"]["video"], 1)
|
||||
self.assertTrue(summary["playbooks"])
|
||||
self.assertTrue(summary["recipes"])
|
||||
|
||||
|
||||
|
||||
@ -16,7 +16,7 @@ class ProcessRuntimeStatusTests(unittest.TestCase):
|
||||
self.assertEqual(normalize_log_text(raw), "line1\nline2\nline3\nline4")
|
||||
self.assertEqual(tail_log_text(raw, 2), "line3\nline4\n")
|
||||
|
||||
def test_summarize_process_activity_marks_streaming_when_ffmpeg_is_active(self) -> None:
|
||||
def test_summarize_process_activity_does_not_mark_idle_ffmpeg_pid_as_pushing(self) -> None:
|
||||
state = summarize_process_activity(
|
||||
"youtube",
|
||||
"online",
|
||||
@ -25,8 +25,22 @@ class ProcessRuntimeStatusTests(unittest.TestCase):
|
||||
log_age_seconds=3.0,
|
||||
ffmpeg_pids=[1234],
|
||||
)
|
||||
self.assertEqual(state["business_status"], "streaming")
|
||||
self.assertTrue(state["is_pushing"])
|
||||
self.assertEqual(state["business_status"], "monitoring")
|
||||
self.assertFalse(state["is_pushing"])
|
||||
self.assertTrue(state["ffmpeg_active"])
|
||||
|
||||
def test_summarize_process_activity_marks_relay_starting_before_progress(self) -> None:
|
||||
state = summarize_process_activity(
|
||||
"youtube",
|
||||
"online",
|
||||
"Starting FFmpeg command for rtmps://a.rtmps.youtube.com/live2/demo-key",
|
||||
"",
|
||||
log_age_seconds=3.0,
|
||||
ffmpeg_pids=[1234],
|
||||
)
|
||||
self.assertEqual(state["business_status"], "relay_starting")
|
||||
self.assertFalse(state["is_pushing"])
|
||||
self.assertTrue(state["ffmpeg_active"])
|
||||
|
||||
def test_summarize_process_activity_marks_waiting_source(self) -> None:
|
||||
state = summarize_process_activity(
|
||||
@ -83,7 +97,7 @@ class ProcessRuntimeStatusTests(unittest.TestCase):
|
||||
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:
|
||||
def test_summarize_process_activity_marks_key_rejected_even_with_residual_pid(self) -> None:
|
||||
state = summarize_process_activity(
|
||||
"youtube",
|
||||
"online",
|
||||
@ -97,8 +111,8 @@ class ProcessRuntimeStatusTests(unittest.TestCase):
|
||||
log_age_seconds=2.0,
|
||||
ffmpeg_pids=[4321],
|
||||
)
|
||||
self.assertEqual(state["business_status"], "streaming")
|
||||
self.assertTrue(state["is_pushing"])
|
||||
self.assertEqual(state["business_status"], "youtube_key_rejected")
|
||||
self.assertFalse(state["is_pushing"])
|
||||
|
||||
def test_summarize_process_activity_marks_streaming_from_recent_ffmpeg_progress(self) -> None:
|
||||
state = summarize_process_activity(
|
||||
|
||||
43
d2ypp2/tests/test_project_metadata.py
Normal file
43
d2ypp2/tests/test_project_metadata.py
Normal file
@ -0,0 +1,43 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def _dependency_names(items: list[str]) -> set[str]:
|
||||
names: set[str] = set()
|
||||
for item in items:
|
||||
head = item.split(";", 1)[0].strip()
|
||||
name = head.split("[", 1)[0]
|
||||
for marker in (">=", "<=", "==", "~=", "!=", ">", "<"):
|
||||
name = name.split(marker, 1)[0]
|
||||
if name:
|
||||
names.add(name.lower())
|
||||
return names
|
||||
|
||||
|
||||
def test_pyproject_declares_control_plane_runtime_dependencies() -> None:
|
||||
pyproject = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))
|
||||
pyproject_deps = _dependency_names(pyproject["project"]["dependencies"])
|
||||
requirements = _dependency_names(
|
||||
[
|
||||
line.strip()
|
||||
for line in (ROOT / "requirements.txt").read_text(encoding="utf-8").splitlines()
|
||||
if line.strip() and not line.lstrip().startswith("#")
|
||||
]
|
||||
)
|
||||
|
||||
required = {
|
||||
"fastapi",
|
||||
"starlette",
|
||||
"pydantic",
|
||||
"uvicorn",
|
||||
"python-multipart",
|
||||
"httpx",
|
||||
"pyyaml",
|
||||
}
|
||||
assert required <= pyproject_deps
|
||||
assert required <= requirements
|
||||
33
d2ypp2/tests/test_web_console_quality_gate.py
Normal file
33
d2ypp2/tests/test_web_console_quality_gate.py
Normal file
@ -0,0 +1,33 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def test_next_build_does_not_skip_lint_or_typecheck() -> None:
|
||||
config = (ROOT / "web-console" / "next.config.mjs").read_text(encoding="utf-8")
|
||||
|
||||
assert "ignoreBuildErrors" not in config
|
||||
assert "ignoreDuringBuilds" not in config
|
||||
|
||||
|
||||
def test_next_config_uses_dev_rewrites_instead_of_middleware() -> None:
|
||||
config = (ROOT / "web-console" / "next.config.mjs").read_text(encoding="utf-8")
|
||||
|
||||
assert not (ROOT / "web-console" / "middleware.ts").exists()
|
||||
assert "nextConfig.rewrites" in config
|
||||
assert "process.env.NODE_ENV === \"development\"" in config
|
||||
assert "/process_monitor" in config
|
||||
assert "/shellcrash/apply_profile" in config
|
||||
|
||||
|
||||
def test_package_scripts_expose_full_project_checks() -> None:
|
||||
root_pkg = json.loads((ROOT / "package.json").read_text(encoding="utf-8"))
|
||||
console_pkg = json.loads((ROOT / "web-console" / "package.json").read_text(encoding="utf-8"))
|
||||
|
||||
assert root_pkg["scripts"]["check"] == "python -m pytest -q && pnpm -C web-console run check"
|
||||
assert console_pkg["scripts"]["typecheck"] == "tsc --noEmit"
|
||||
assert console_pkg["scripts"]["check"] == "pnpm run lint && pnpm run typecheck && pnpm run build"
|
||||
@ -42,6 +42,64 @@ class WebDynamicProcessesTests(unittest.TestCase):
|
||||
pm2_names = {row["pm2"] for row in entries}
|
||||
self.assertIn("youtube2__lane1", pm2_names)
|
||||
|
||||
def test_studio_ops_playbook_runs_snapshot_and_service_actions(self) -> None:
|
||||
calls: list[tuple[str, str]] = []
|
||||
|
||||
async def fake_service_action(service: str, action: str) -> dict[str, object]:
|
||||
calls.append((service, action))
|
||||
return {
|
||||
"service_id": service,
|
||||
"status": "running",
|
||||
"running": True,
|
||||
"available": True,
|
||||
"message": f"{service} {action}",
|
||||
}
|
||||
|
||||
snapshot = {"snapshot": {"id": "unit.zip", "name": "unit.zip"}}
|
||||
summary = {"playbooks": [{"id": "youtube-live-ready"}], "doctor": {"score": 100}}
|
||||
with patch("web.create_system_snapshot", return_value=snapshot) as create_snapshot:
|
||||
with patch("web.service_action", new=AsyncMock(side_effect=fake_service_action)):
|
||||
with patch("web.query_services", new=AsyncMock(return_value=[])):
|
||||
with patch("web.deployment_report", return_value={"ready": True}):
|
||||
with patch("web.studio_ops_summary", return_value=summary):
|
||||
payload = asyncio.run(
|
||||
web.post_studio_ops_playbook(web.StudioPlaybookRunBody(playbook_id="youtube-live-ready"))
|
||||
)
|
||||
|
||||
create_snapshot.assert_called_once()
|
||||
self.assertEqual(calls, [("shellcrash", "restart"), ("srs", "start"), ("neko", "start")])
|
||||
self.assertEqual(payload["failed"], 0)
|
||||
self.assertEqual(payload["snapshot"]["id"], "unit.zip")
|
||||
self.assertEqual(payload["summary"], summary)
|
||||
|
||||
def test_studio_ops_playbook_unknown_id_returns_404(self) -> None:
|
||||
response = asyncio.run(web.post_studio_ops_playbook(web.StudioPlaybookRunBody(playbook_id="missing-playbook")))
|
||||
|
||||
self.assertEqual(response.status_code, 404)
|
||||
self.assertIn("Unknown playbook", _json_body(response)["error"])
|
||||
|
||||
def test_studio_ops_playbook_counts_unavailable_service_action_as_failed(self) -> None:
|
||||
async def fake_service_action(service: str, action: str) -> dict[str, object]:
|
||||
return {
|
||||
"service_id": service,
|
||||
"status": "unavailable",
|
||||
"running": False,
|
||||
"available": False,
|
||||
"message": "Service controller script is missing",
|
||||
}
|
||||
|
||||
with patch("web.create_system_snapshot", return_value={"snapshot": {"id": "unit.zip"}}):
|
||||
with patch("web.service_action", new=AsyncMock(side_effect=fake_service_action)):
|
||||
with patch("web.query_services", new=AsyncMock(return_value=[])):
|
||||
with patch("web.deployment_report", return_value={"ready": False}):
|
||||
with patch("web.studio_ops_summary", return_value={"playbooks": []}):
|
||||
payload = asyncio.run(
|
||||
web.post_studio_ops_playbook(web.StudioPlaybookRunBody(playbook_id="tiktok-hdmi-ready"))
|
||||
)
|
||||
|
||||
self.assertEqual(payload["failed"], 2)
|
||||
self.assertEqual(payload["message"], "Playbook completed with errors")
|
||||
|
||||
def test_process_monitor_entries_default_pm2_name_when_missing(self) -> None:
|
||||
channels = [{"id": "lane2", "name": "Lane 2"}]
|
||||
with patch("web.get_youtube_pro_channels", return_value=channels):
|
||||
|
||||
@ -4,7 +4,7 @@ import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from src.youtube_config_paths import resolve_youtube_style_config_paths
|
||||
from src.youtube_config_paths import is_youtube_pro_pm2, resolve_youtube_style_config_paths
|
||||
|
||||
|
||||
class YoutubeConfigPathTests(unittest.TestCase):
|
||||
@ -58,6 +58,22 @@ class YoutubeConfigPathTests(unittest.TestCase):
|
||||
self.assertEqual(yt, str(managed_yt))
|
||||
self.assertEqual(url, str(cfg / "URL_config.ini"))
|
||||
|
||||
def test_pro_lane_never_falls_back_to_legacy_url(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
cfg = root / "config"
|
||||
cfg.mkdir(parents=True, exist_ok=True)
|
||||
(cfg / "youtube.ini").write_text("[youtube]\nkey = legacy\n", encoding="utf-8")
|
||||
(cfg / "URL_config.ini").write_text("https://live.douyin.com/legacy\n", encoding="utf-8")
|
||||
managed_yt = cfg / "youtube.youtube2__lane1.ini"
|
||||
managed_yt.write_text("[youtube]\nkey = lane1\n", encoding="utf-8")
|
||||
|
||||
yt, url = resolve_youtube_style_config_paths(root, "youtube2__lane1")
|
||||
|
||||
self.assertEqual(yt, str(managed_yt))
|
||||
self.assertEqual(url, str(cfg / "URL_config.youtube2__lane1.ini"))
|
||||
self.assertTrue(is_youtube_pro_pm2("youtube2__lane1"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
40
d2ypp2/tests/test_youtube_ingest_auth.py
Normal file
40
d2ypp2/tests/test_youtube_ingest_auth.py
Normal file
@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from src.youtube_ingest_auth import ingest_auth_required, verify_ingest_payload
|
||||
|
||||
|
||||
class YoutubeIngestAuthTests(unittest.TestCase):
|
||||
def test_auth_disabled_without_token(self) -> None:
|
||||
with mock.patch.dict(os.environ, {"YOUTUBE_INGEST_REQUIRE_AUTH": "0"}, clear=False):
|
||||
self.assertFalse(ingest_auth_required())
|
||||
ok, reason = verify_ingest_payload({})
|
||||
self.assertTrue(ok)
|
||||
self.assertEqual(reason, "")
|
||||
|
||||
def test_auth_accepts_matching_token(self) -> None:
|
||||
with mock.patch.dict(
|
||||
os.environ,
|
||||
{"YOUTUBE_INGEST_TOKEN": "secret-token", "YOUTUBE_INGEST_REQUIRE_AUTH": "1"},
|
||||
clear=False,
|
||||
):
|
||||
ok, reason = verify_ingest_payload({"ingest_token": "secret-token"})
|
||||
self.assertTrue(ok)
|
||||
self.assertEqual(reason, "")
|
||||
|
||||
def test_auth_rejects_missing_token(self) -> None:
|
||||
with mock.patch.dict(
|
||||
os.environ,
|
||||
{"YOUTUBE_INGEST_TOKEN": "secret-token", "YOUTUBE_INGEST_REQUIRE_AUTH": "1"},
|
||||
clear=False,
|
||||
):
|
||||
ok, reason = verify_ingest_payload({})
|
||||
self.assertFalse(ok)
|
||||
self.assertIn("invalid", reason.lower())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -6,6 +6,7 @@ from pathlib import Path
|
||||
|
||||
from src.youtube_live_store import (
|
||||
close_live_event,
|
||||
_connect,
|
||||
get_live_event,
|
||||
ingest_browser_telemetry,
|
||||
list_live_events,
|
||||
@ -16,6 +17,17 @@ from src.youtube_live_store import (
|
||||
|
||||
|
||||
class YoutubeLiveStoreTests(unittest.TestCase):
|
||||
def test_connection_enables_foreign_keys_and_wal_when_supported(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
db = Path(td) / "hub_state.sqlite"
|
||||
conn = _connect(db)
|
||||
try:
|
||||
self.assertEqual(conn.execute("PRAGMA foreign_keys").fetchone()[0], 1)
|
||||
self.assertEqual(conn.execute("PRAGMA busy_timeout").fetchone()[0], 12000)
|
||||
self.assertIn(conn.execute("PRAGMA journal_mode").fetchone()[0].lower(), {"wal", "memory"})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def test_control_action_creates_traceable_event(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
db = Path(td) / "hub_state.sqlite"
|
||||
@ -103,6 +115,35 @@ class YoutubeLiveStoreTests(unittest.TestCase):
|
||||
self.assertEqual(detail["status"], "ended")
|
||||
self.assertIsNotNone(detail["ended_at"])
|
||||
|
||||
def test_relay_starting_process_observation_keeps_active_event(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
db = Path(td) / "hub_state.sqlite"
|
||||
created = record_control_action(
|
||||
"youtube",
|
||||
"start",
|
||||
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",
|
||||
{
|
||||
"process_status": "online",
|
||||
"business_status": "relay_starting",
|
||||
"business_note": "FFmpeg worker is present, but no video progress has been observed yet",
|
||||
"ffmpeg_active": True,
|
||||
"is_pushing": False,
|
||||
},
|
||||
url_lines="https://live.douyin.com/456789\n",
|
||||
db_path=db,
|
||||
)
|
||||
|
||||
self.assertNotIn("count", result)
|
||||
summary = youtube_live_summary(db_path=db)
|
||||
self.assertEqual(summary["stats"]["active_events"], 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -9,6 +9,7 @@ from douyin_youtube_ffplay import (
|
||||
_ffmpeg_env_with_push_proxy,
|
||||
_ffmpeg_speed_value,
|
||||
_ffmpeg_stats_args,
|
||||
_h264_vaapi_video_args,
|
||||
_looks_like_invalid_ts_drop,
|
||||
_normalize_push_proxy_mode,
|
||||
_proxychains_proxy_line,
|
||||
@ -154,6 +155,20 @@ class YoutubePushConfigTests(unittest.TestCase):
|
||||
"socks5 127.0.0.1 7891",
|
||||
)
|
||||
|
||||
def test_h264_vaapi_uses_cqp_by_default(self) -> None:
|
||||
with patch.dict("os.environ", {}, clear=True):
|
||||
args, label = _h264_vaapi_video_args()
|
||||
|
||||
self.assertEqual(args, ["-rc_mode", "CQP", "-qp", "24", "-profile:v", "high"])
|
||||
self.assertEqual(label, "CQP qp=24")
|
||||
|
||||
def test_h264_vaapi_qp_can_come_from_hardware_env(self) -> None:
|
||||
with patch.dict("os.environ", {}, clear=True):
|
||||
args, label = _h264_vaapi_video_args({"LIVE_VAAPI_QP": "26"})
|
||||
|
||||
self.assertEqual(args, ["-rc_mode", "CQP", "-qp", "26", "-profile:v", "high"])
|
||||
self.assertEqual(label, "CQP qp=26")
|
||||
|
||||
def test_proxychains_ffmpeg_falls_back_from_static_to_dynamic_binary(self) -> None:
|
||||
def fake_which(name: str) -> str | None:
|
||||
if name == "proxychains4":
|
||||
|
||||
@ -54,6 +54,52 @@ class YoutubeQualityGuardTests(unittest.TestCase):
|
||||
self.assertIn("FFmpeg 未检测到", report["lanes"][0]["issues"][0]["text"])
|
||||
self.assertEqual(report["lanes"][0]["source_display"], "抖音直播间 123")
|
||||
|
||||
def test_quality_report_ignores_stale_ffmpeg_metrics_when_lane_is_not_pushing(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": "[FFmpeg] frame=15733 fps=29 time=00:08:44.40 bitrate=2161.8kbits/s speed=0.974x",
|
||||
"recent_error": "",
|
||||
}
|
||||
],
|
||||
config_by_process={
|
||||
"youtube": {
|
||||
"youtube_ini_text": "[youtube]\nkey = demo\nrtmps = 1\n",
|
||||
"url_lines": "https://live.douyin.com/123\n",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
self.assertEqual(report["summary"]["pushing_lanes"], 0)
|
||||
self.assertNotIn("frame", report["lanes"][0]["metrics"])
|
||||
self.assertNotIn("speed", report["lanes"][0]["metrics"])
|
||||
|
||||
def test_quality_report_does_not_count_studio_events_without_pushing_lane(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": "",
|
||||
"recent_error": "",
|
||||
}
|
||||
],
|
||||
live_summary={"stats": {"active_events": 4, "sample_count": 100, "viewer_peak": 0}},
|
||||
)
|
||||
|
||||
self.assertEqual(report["summary"]["pushing_lanes"], 0)
|
||||
self.assertEqual(report["summary"]["active_events"], 4)
|
||||
|
||||
def test_quality_report_flags_ffmpeg_running_faster_than_realtime(self) -> None:
|
||||
report = build_youtube_quality_guard_report(
|
||||
[
|
||||
|
||||
@ -1,25 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect("10.88.0.4", username="eric", password="4669805", timeout=20)
|
||||
B = "/home/eric/d2ypp2-src"
|
||||
|
||||
|
||||
def run(cmd: str) -> str:
|
||||
_, o, e = c.exec_command(f"export LC_ALL=C.UTF-8; {cmd}", timeout=90, get_pty=True)
|
||||
return (o.read() + e.read()).decode("utf-8", "replace")
|
||||
|
||||
|
||||
for label, cmd in [
|
||||
("proxychains_nameerror", f"grep -h '_proxychains_config_for_push' {B}/.pm2/logs/youtube2__*-err.log 2>/dev/null | tail -5 || echo none"),
|
||||
("duplicate_option", f"grep -h 'DuplicateOptionError' {B}/.pm2/logs/youtube2__*-err.log 2>/dev/null | tail -3 || echo none"),
|
||||
("outer_exception", f"grep -h '外层异常' {B}/.pm2/logs/youtube2__*-out.log 2>/dev/null | tail -5 || echo none"),
|
||||
("ffmpeg", "pgrep -af 'ffmpeg.*rtmps' | grep -v pgrep | head -3"),
|
||||
("recent_out", f"tail -8 {B}/.pm2/logs/youtube2__ch_mpwri36r_z5lm2-out.log 2>/dev/null"),
|
||||
]:
|
||||
print(f"=== {label} ===")
|
||||
print(run(cmd)[:1500])
|
||||
print()
|
||||
c.close()
|
||||
@ -1,40 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import paramiko
|
||||
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect("10.88.0.4", username="eric", password="4669805", timeout=20)
|
||||
B = "/home/eric/d2ypp2-src"
|
||||
|
||||
|
||||
def run(cmd: str, timeout: int = 90) -> str:
|
||||
_, o, e = c.exec_command(f"export LC_ALL=C.UTF-8; {cmd}", timeout=timeout, get_pty=True)
|
||||
return (o.read() + e.read()).decode("utf-8", "replace")
|
||||
|
||||
|
||||
raw = run("curl -sS -m 12 'http://127.0.0.1:8001/process_monitor?family=youtube'")
|
||||
entries = json.loads(raw).get("entries", [])
|
||||
print("=== all youtube lanes ===")
|
||||
for row in entries:
|
||||
pm2 = row.get("pm2", "")
|
||||
if not pm2.startswith("youtube"):
|
||||
continue
|
||||
print(
|
||||
pm2,
|
||||
row.get("business_status"),
|
||||
f"pushing={row.get('is_pushing')}",
|
||||
f"speed={row.get('ffmpeg_speed')}",
|
||||
repr((row.get("source_display") or "")[:50]),
|
||||
)
|
||||
|
||||
print("\n=== ffmpeg ===")
|
||||
print(run("pgrep -af ffmpeg | grep -v pgrep | head -6"))
|
||||
|
||||
print("\n=== live profile lines ===")
|
||||
print(run(f"grep -h 'YouTube Live profile' {B}/.pm2/logs/youtube2__*-out.log 2>/dev/null | tail -6"))
|
||||
|
||||
print("\n=== recent errors ===")
|
||||
print(run(f"grep -hE '外层异常|NameError|DuplicateOption' {B}/.pm2/logs/youtube2__*-err.log 2>/dev/null | tail -5 || echo none"))
|
||||
|
||||
c.close()
|
||||
@ -1,42 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS, BASE = "10.88.0.4", "eric", "4669805", "/home/eric/d2ypp2-src"
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=20)
|
||||
|
||||
|
||||
def run(cmd: str) -> str:
|
||||
_, o, e = c.exec_command(f"export LC_ALL=C.UTF-8; {cmd}", timeout=90, get_pty=True)
|
||||
return (o.read() + e.read()).decode("utf-8", "replace")
|
||||
|
||||
|
||||
checks = {
|
||||
"health": run("curl -sf -m 8 http://127.0.0.1:8001/health"),
|
||||
"copy_fn": run(f"grep -c _resolve_stream_copy_plan {BASE}/douyin_youtube_ffplay.py 2>/dev/null || echo 0").strip(),
|
||||
"key_guard": run(f"grep -c _looks_like_youtube_output_rejected {BASE}/douyin_youtube_ffplay.py").strip(),
|
||||
"relay": run(f"grep -c relay_strategy {BASE}/config/hardware-profile.json 2>/dev/null || echo 0").strip(),
|
||||
"ffmpeg": run("pgrep -af 'ffmpeg.*rtmps' | grep -v pgrep | head -3"),
|
||||
"profile": run(f"grep -h 'YouTube Live profile' {BASE}/.pm2/logs/youtube2__*-out.log 2>/dev/null | tail -4"),
|
||||
"speed": run(f"grep -h 'speed=' {BASE}/.pm2/logs/youtube2__*-out.log 2>/dev/null | tail -4"),
|
||||
"qg": run(
|
||||
"curl -sS -m 12 http://127.0.0.1:8001/hub/youtube/quality_guard | "
|
||||
"python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('ffmpeg_profile',{}).get('target','?'))\""
|
||||
).strip(),
|
||||
}
|
||||
print(json.dumps(checks, ensure_ascii=False, indent=2))
|
||||
raw = run("curl -sS -m 12 'http://127.0.0.1:8001/process_monitor?family=youtube'")
|
||||
for row in json.loads(raw).get("entries", []):
|
||||
pm2 = row.get("pm2", "")
|
||||
if pm2.startswith("youtube2"):
|
||||
print(pm2, row.get("business_status"), row.get("is_pushing"), row.get("ffmpeg_speed"))
|
||||
|
||||
ok = (
|
||||
checks["copy_fn"] in {"0", ""}
|
||||
and checks["relay"] in {"0", ""}
|
||||
and "libx264" in (checks["ffmpeg"] + checks["profile"])
|
||||
)
|
||||
print("REGRESSION:", "PASS" if ok else "PARTIAL")
|
||||
c.close()
|
||||
@ -1,40 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
import sys
|
||||
|
||||
HOSTS = [
|
||||
("10.88.0.4", "4669805", "/home/eric/d2ypp2-src"),
|
||||
("10.88.0.5", "4669805", "/opt/live/d2ypp"),
|
||||
]
|
||||
|
||||
|
||||
def run(host: str, pw: str, cmd: str) -> str:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(host, username="eric", password=pw, timeout=15)
|
||||
_, o, e = c.exec_command(cmd, timeout=90)
|
||||
out = (o.read() + e.read()).decode("utf-8", "replace")
|
||||
c.close()
|
||||
return out
|
||||
|
||||
|
||||
def main() -> None:
|
||||
for host, pw, base in HOSTS:
|
||||
print(f"\n{'='*60}\n{host} {base}\n{'='*60}")
|
||||
cmds = {
|
||||
"md5": f"md5sum {base}/douyin_youtube_ffplay.py",
|
||||
"re_flags": f"grep -nE 'readrate|wallclock| -re |\\-re,' {base}/douyin_youtube_ffplay.py | head -15",
|
||||
"lanes": f"ls -1 {base}/config/youtube.youtube2__*.ini 2>/dev/null",
|
||||
"keys": f"grep -H '^key' {base}/config/youtube.youtube2__*.ini 2>/dev/null",
|
||||
"ffmpeg": "ps auxww | grep 'ffmpeg.*rtmps' | grep -v grep",
|
||||
"speed": f"grep 'speed=' {base}/.pm2/logs/youtube2__*-out.log 2>/dev/null | tail -4",
|
||||
"lane1_tail": f"tail -15 {base}/.pm2/logs/$(ls -1 {base}/.pm2/logs/youtube2__*-out.log 2>/dev/null | head -1) 2>/dev/null",
|
||||
"monitor": "curl -sS -m 10 'http://127.0.0.1:8001/process_monitor?family=youtube&light=1' 2>/dev/null | python3 -c \"import json,sys; d=json.load(sys.stdin); [print(e.get('pm2'), e.get('business_status'), 'speed='+str(e.get('ffmpeg_speed'))) for e in d.get('entries',[])]\" 2>/dev/null",
|
||||
}
|
||||
for name, cmd in cmds.items():
|
||||
sys.stdout.buffer.write(f"\n--- {name} ---\n".encode())
|
||||
sys.stdout.buffer.write(run(host, pw, cmd).encode("utf-8", "replace"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,25 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko, sys
|
||||
c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect('10.88.0.5', username='eric', password='4669805', timeout=15)
|
||||
base='/opt/live/d2ypp'
|
||||
lane='youtube2__ch_mp9mm36r_2wn0r'
|
||||
for name, cmd in [
|
||||
('url1', f'head -20 {base}/config/URL_config.{lane}.ini'),
|
||||
('url2', f'head -20 {base}/config/URL_config.youtube2__ch_mp9n7yu2_83vci.ini'),
|
||||
('url4', f'head -20 /home/eric/d2ypp2-src/config/URL_config.{lane}.ini 2>/dev/null || head -20 /home/eric/d2ypp2-src/config/URL_config.youtube2__ch_mp9mm36r_2wn0r.ini 2>/dev/null'),
|
||||
]:
|
||||
pass
|
||||
# host04 compare via separate connect
|
||||
c4=paramiko.SSHClient(); c4.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c4.connect('10.88.0.4', username='eric', password='4669805', timeout=15)
|
||||
for host, cli, path in [
|
||||
('05', c, f'{base}/config/URL_config.{lane}.ini'),
|
||||
('05lane2', c, f'{base}/config/URL_config.youtube2__ch_mp9n7yu2_83vci.ini'),
|
||||
('04', c4, f'/home/eric/d2ypp2-src/config/URL_config.{lane}.ini'),
|
||||
]:
|
||||
print(f'=== {host} ===')
|
||||
_,o,e=cli.exec_command(f'wc -l {path}; head -8 {path}', timeout=30)
|
||||
sys.stdout.buffer.write((o.read()+e.read()).decode('utf-8','replace').encode('utf-8','replace'))
|
||||
sys.stdout.buffer.write(b'\n')
|
||||
c.close(); c4.close()
|
||||
@ -1,50 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
|
||||
HOST, PW = "10.88.0.3", "Xiao4669805"
|
||||
BASE = "/home/eric/d2ypp2-src"
|
||||
|
||||
CMDS = [
|
||||
("docker_ps", "docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' 2>/dev/null | grep -i neko; true"),
|
||||
("curl_9200", "curl -sS -m 8 -o /dev/null -w '9200 http=%{http_code} time=%{time_total}\n' http://127.0.0.1:9200/ 2>&1; true"),
|
||||
("curl_9201", "curl -sS -m 8 -o /dev/null -w '9201 http=%{http_code} time=%{time_total}\n' http://127.0.0.1:9201/ 2>&1; true"),
|
||||
("curl_wg", "curl -sS -m 8 -o /dev/null -w '10.88.0.3:9200 http=%{http_code}\n' http://10.88.0.3:9200/ 2>&1; true"),
|
||||
("ss_ports", "ss -tlnp 2>/dev/null | grep -E ':9200|:9201' || echo no_listener"),
|
||||
("inspect1", "docker inspect live-neko-1 --format '{{.State.Status}} health={{if .State.Health}}{{.State.Health.Status}}{{end}} err={{.State.Error}}' 2>/dev/null || echo missing"),
|
||||
("inspect2", "docker inspect live-neko-2 --format '{{.State.Status}} health={{if .State.Health}}{{.State.Health.Status}}{{end}} err={{.State.Error}}' 2>/dev/null || echo missing"),
|
||||
("logs1", "docker logs --tail 50 live-neko-1 2>&1"),
|
||||
("logs2", "docker logs --tail 50 live-neko-2 2>&1"),
|
||||
(
|
||||
"neko_status",
|
||||
f"cd {BASE} && . scripts/linux/lib/common.sh && load_env && bash scripts/linux/service_ctl.sh neko status 2>&1 | head -80",
|
||||
),
|
||||
(
|
||||
"stack_env",
|
||||
f"grep -E 'NEKO|ENABLE_NEKO|SHELLCRASH|WEBRTC' {BASE}/config/system-stack.env 2>/dev/null | head -40 || echo no_env",
|
||||
),
|
||||
(
|
||||
"compose",
|
||||
f"ls -la {BASE}/services/neko/*.yml {BASE}/services/neko/*.yaml 2>/dev/null; "
|
||||
f"grep -E '9200|9201|NEKO|proxy' {BASE}/services/neko/docker-compose.yml 2>/dev/null | head -30",
|
||||
),
|
||||
("iptables", "sudo -S -p '' iptables -L INPUT -n 2>/dev/null | head -20 || true"),
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username="eric", password=PW, timeout=15)
|
||||
for name, cmd in CMDS:
|
||||
print(f"\n=== {name} ===")
|
||||
stdin, stdout, stderr = c.exec_command(cmd, timeout=90, get_pty=True)
|
||||
if name == "iptables":
|
||||
stdin.write(PW + "\n")
|
||||
stdin.flush()
|
||||
out = (stdout.read() + stderr.read()).decode("utf-8", "replace")
|
||||
print(out[:4000].encode("ascii", "backslashreplace").decode())
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,26 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS, BASE = "10.88.0.4", "eric", "4669805", "/home/eric/d2ypp2-src"
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=20)
|
||||
|
||||
|
||||
def run(cmd: str, timeout: int = 120) -> str:
|
||||
_, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True)
|
||||
return (o.read() + e.read()).decode("utf-8", "replace")
|
||||
|
||||
|
||||
for cmd in [
|
||||
"systemctl is-active live-console.service",
|
||||
"systemctl status live-console.service --no-pager -n 30",
|
||||
"journalctl -u live-console.service -n 50 --no-pager",
|
||||
f"cd {BASE} && . .venv/bin/activate && python -m py_compile web.py douyin_youtube_ffplay.py youtube.py",
|
||||
f"grep relay_strategy {BASE}/config/hardware-profile.json 2>/dev/null || echo no_relay",
|
||||
]:
|
||||
print("===", cmd[:100])
|
||||
print(run(cmd)[:4000])
|
||||
print()
|
||||
|
||||
c.close()
|
||||
@ -1,33 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
import sys
|
||||
|
||||
HOST, PW, BASE = "10.88.0.5", "4669805", "/opt/live/d2ypp"
|
||||
|
||||
CMDS = [
|
||||
("lanes", f"ls -1 {BASE}/config/youtube.youtube2__*.ini"),
|
||||
("keys", f"grep -H '^key' {BASE}/config/youtube.youtube2__*.ini"),
|
||||
("pm2", "pm2 list 2>/dev/null || true"),
|
||||
("logs", f"ls -lt {BASE}/.pm2/logs/youtube2__*-out.log 2>/dev/null | head -5"),
|
||||
("speed", f"grep -E 'speed=|invalid dropping|YouTube Live profile|fast_audio|LIVE_VIDEO' {BASE}/.pm2/logs/youtube2__*-out.log 2>/dev/null | tail -50"),
|
||||
("tail1", f"tail -60 $(ls -t {BASE}/.pm2/logs/youtube2__*-out.log 2>/dev/null | head -1) 2>/dev/null"),
|
||||
("ffmpeg", "ps auxww | grep 'ffmpeg.*rtmps' | grep -v grep"),
|
||||
("vaapi", "ffmpeg -hide_banner -encoders 2>/dev/null | grep h264_vaapi; ls -la /dev/dri/renderD128 2>/dev/null"),
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username="eric", password=PW, timeout=15)
|
||||
for name, cmd in CMDS:
|
||||
sys.stdout.buffer.write(f"\n=== {name} ===\n".encode())
|
||||
_, stdout, stderr = c.exec_command(cmd, timeout=90)
|
||||
out = (stdout.read() + stderr.read()).decode("utf-8", "replace")
|
||||
sys.stdout.buffer.write(out.encode("utf-8", "replace"))
|
||||
sys.stdout.buffer.write(b"\n")
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,63 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Point host 10.88.0.3 Neko at the legacy profile directory and restart."""
|
||||
import paramiko
|
||||
import sys
|
||||
|
||||
HOST, PW = "10.88.0.3", "Xiao4669805"
|
||||
BASE = "/home/eric/d2ypp2-src"
|
||||
OLD = "/home/eric/live-d2ypp-neko-runtime/profiles/google-chrome-profile-v2"
|
||||
ENV_FILE = f"{BASE}/config/system-stack.env"
|
||||
|
||||
|
||||
def run(client: paramiko.SSHClient, cmd: str, timeout: int = 120) -> str:
|
||||
_, stdout, stderr = client.exec_command(cmd, timeout=timeout)
|
||||
out = (stdout.read() + stderr.read()).decode("utf-8", "replace")
|
||||
sys.stdout.buffer.write(out.encode("utf-8", "replace"))
|
||||
sys.stdout.buffer.write(b"\n")
|
||||
sys.stdout.flush()
|
||||
return out
|
||||
|
||||
|
||||
def sudo(client: paramiko.SSHClient, cmd: str, timeout: int = 120) -> str:
|
||||
return run(client, f"echo {PW!r} | sudo -S {cmd}", timeout=timeout)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect(HOST, username="eric", password=PW, timeout=15)
|
||||
|
||||
print("=== patch system-stack.env ===")
|
||||
sudo(
|
||||
client,
|
||||
f"sed -i 's|^NEKO_PROFILE_HOST_DIR=.*|NEKO_PROFILE_HOST_DIR={OLD}|' {ENV_FILE}",
|
||||
)
|
||||
print(run(client, f"grep NEKO_PROFILE {ENV_FILE}"))
|
||||
|
||||
print("=== restart neko ===")
|
||||
run(
|
||||
client,
|
||||
f"cd {BASE} && . scripts/linux/lib/common.sh && load_env && "
|
||||
"bash scripts/linux/service_ctl.sh neko restart 2>&1 | tail -25",
|
||||
timeout=180,
|
||||
)
|
||||
|
||||
print("=== verify ===")
|
||||
run(
|
||||
client,
|
||||
"docker inspect live-neko-1 live-neko-2 "
|
||||
"--format '{{.Name}} profile={{range .Mounts}}"
|
||||
"{{if eq .Destination \"/home/neko/.config/google-chrome\"}}{{.Source}}{{end}}"
|
||||
"{{end}}'",
|
||||
)
|
||||
run(
|
||||
client,
|
||||
f"cd {BASE} && . scripts/linux/lib/common.sh && load_env && "
|
||||
"bash scripts/linux/service_ctl.sh neko status 2>&1 | head -6",
|
||||
)
|
||||
|
||||
client.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,22 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
import sys
|
||||
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect("10.88.0.5", username="eric", password="4669805", timeout=15)
|
||||
log1 = "/opt/live/d2ypp/.pm2/logs/youtube2__ch_mp9mm36r_2wn0r-out.log"
|
||||
log2 = "/opt/live/d2ypp/.pm2/logs/youtube2__ch_mp9n7yu2_83vci-out.log"
|
||||
cmds = [
|
||||
("lane1_speed", f"grep 'speed=' {log1} | tail -20"),
|
||||
("lane1_drop_count", f"grep -c 'invalid dropping' {log1} || true"),
|
||||
("lane1_profile", f"grep -E 'YouTube Live profile|启动 YouTube|libx264|vaapi|stream copy' {log1} | tail -10"),
|
||||
("lane2_drop_count", f"grep -c 'invalid dropping' {log2} || true"),
|
||||
("lane2_speed", f"grep 'speed=' {log2} | tail -5"),
|
||||
]
|
||||
for name, cmd in cmds:
|
||||
sys.stdout.buffer.write(f"\n=== {name} ===\n".encode())
|
||||
_, stdout, stderr = c.exec_command(cmd, timeout=60)
|
||||
sys.stdout.buffer.write((stdout.read() + stderr.read()).decode("utf-8", "replace").encode("utf-8", "replace"))
|
||||
sys.stdout.buffer.write(b"\n")
|
||||
c.close()
|
||||
@ -1,16 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko, sys
|
||||
c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect('10.88.0.5', username='eric', password='4669805', timeout=15)
|
||||
log='/opt/live/d2ypp/.pm2/logs/youtube2__ch_mp9mm36r_2wn0r-out.log'
|
||||
cmds=[
|
||||
('tail', f'tail -40 {log}'),
|
||||
('ffmpeg', "ps auxww | grep ffmpeg | grep -v grep"),
|
||||
('monitor', "curl -sS -m 10 'http://127.0.0.1:8001/process_monitor?family=youtube&light=1' | python3 -c \"import json,sys; d=json.load(sys.stdin); print('\\n'.join(f\\\"{e.get('pm2')}: {e.get('business_status')} speed={e.get('ffmpeg_speed')} proc={e.get('process_status')}\\\" for e in d.get('entries',[])))\" 2>&1"),
|
||||
]
|
||||
for n,cmd in cmds:
|
||||
print('===',n,'===')
|
||||
_,o,e=c.exec_command(cmd, timeout=60)
|
||||
sys.stdout.buffer.write((o.read()+e.read()).decode('utf-8','replace').encode('utf-8','replace'))
|
||||
sys.stdout.buffer.write(b'\n')
|
||||
c.close()
|
||||
@ -1,55 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import glob
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
base = sys.argv[1]
|
||||
|
||||
def patch_ini() -> int:
|
||||
removed = 0
|
||||
for path in sorted(glob.glob(f"{base}/config/youtube.youtube2__*.ini")):
|
||||
lines_out = []
|
||||
for line in Path(path).read_text(encoding="utf-8-sig").splitlines():
|
||||
key = line.split("=", 1)[0].strip().lower()
|
||||
if key in {"video_mode", "bitrate"}:
|
||||
removed += 1
|
||||
continue
|
||||
lines_out.append(line)
|
||||
Path(path).write_text("\n".join(lines_out).rstrip() + "\n", encoding="utf-8")
|
||||
return removed
|
||||
|
||||
|
||||
def patch_profile() -> bool:
|
||||
p = Path(f"{base}/config/hardware-profile.json")
|
||||
if not p.is_file():
|
||||
return False
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
if isinstance(data, dict) and "relay_strategy" in data:
|
||||
data.pop("relay_strategy", None)
|
||||
p.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def patch_env() -> int:
|
||||
p = Path(f"{base}/config/hardware.env")
|
||||
if not p.is_file():
|
||||
return 0
|
||||
kept = []
|
||||
removed = 0
|
||||
for line in p.read_text(encoding="utf-8-sig").splitlines():
|
||||
key = line.split("=", 1)[0].strip()
|
||||
if key.startswith("LIVE_RELAY_"):
|
||||
removed += 1
|
||||
continue
|
||||
kept.append(line)
|
||||
p.write_text("\n".join(kept).rstrip() + "\n", encoding="utf-8")
|
||||
return removed
|
||||
|
||||
|
||||
text = Path(f"{base}/douyin_youtube_ffplay.py").read_text(encoding="utf-8", errors="ignore")
|
||||
print("ini_removed", patch_ini())
|
||||
print("relay_strategy_removed", patch_profile())
|
||||
print("relay_env_removed", patch_env())
|
||||
print("has_stream_copy_fn", "_resolve_stream_copy_plan" in text)
|
||||
@ -1,28 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS, BASE = "10.88.0.4", "eric", "4669805", "/home/eric/d2ypp2-src"
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=20)
|
||||
|
||||
|
||||
def run(cmd: str, timeout: int = 120) -> str:
|
||||
_, o, e = c.exec_command(f"export LC_ALL=C.UTF-8; {cmd}", timeout=timeout, get_pty=True)
|
||||
return (o.read() + e.read()).decode("utf-8", "replace")
|
||||
|
||||
|
||||
cmds = [
|
||||
f"head -30 {BASE}/config/youtube.youtube2__ch_mpwri36r_z5lm2.ini",
|
||||
f"grep -i douyin {BASE}/config/config.ini 2>/dev/null | head -3 || echo no_douyin_cookie",
|
||||
f"grep -E 'push_proxy|proxy' {BASE}/config/youtube.youtube2__ch_mpwri36r_z5lm2.ini | head -5",
|
||||
f"cd {BASE} && . .venv/bin/activate && python tools/test_douyin_fetch.py https://live.douyin.com/29155980665 2>&1",
|
||||
f"grep -c 'def _proxychains_config_for_push' {BASE}/douyin_youtube_ffplay.py",
|
||||
f"grep -c 'Douyin web API failed' {BASE}/src/spider.py || echo 0",
|
||||
]
|
||||
for cmd in cmds:
|
||||
print("===", cmd[:100])
|
||||
print(run(cmd)[:2500])
|
||||
print()
|
||||
|
||||
c.close()
|
||||
@ -142,7 +142,6 @@ FILES = [
|
||||
"web-console/app/globals.css",
|
||||
"web-console/app/layout.tsx",
|
||||
"web-console/app/page.tsx",
|
||||
"web-console/middleware.ts",
|
||||
"web-console/components/OverviewCharts.tsx",
|
||||
"web-console/components/live-product/LiveControlApp.tsx",
|
||||
"web-console/components/live-product/LiveAndroidWorkstation.tsx",
|
||||
|
||||
@ -10,17 +10,19 @@ import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
BASE = "/home/eric/d2ypp2-src"
|
||||
TUIC3 = "5d723acc-singbox_tuic3"
|
||||
SHELLCRASH_PUSH_NODE = "1d2da142-singbox_tuic5"
|
||||
NEKO_PROXY_NODE = "proxycheap"
|
||||
|
||||
HARDWARE_ENV = """LIVE_HW_DECODER=vaapi
|
||||
LIVE_HDMI_PLAYER=mpv-drm
|
||||
LIVE_BROWSER_HWACCEL=auto
|
||||
LIVE_STABILITY_MODE=balanced
|
||||
# LIVE_VIDEO_ENCODER= # optional: h264_v4l2m2m / h264_rkmpp when ffmpeg supports it
|
||||
LIVE_VIDEO_ENCODER=h264_vaapi
|
||||
LIVE_VAAPI_QP=24
|
||||
"""
|
||||
|
||||
STACK_PATCH = {
|
||||
"SHELLCRASH_NEKO_PROXY_NODE": TUIC3,
|
||||
"SHELLCRASH_NEKO_PROXY_NODE": NEKO_PROXY_NODE,
|
||||
"SHELLCRASH_ATTACH_WHEN_DIRECT_OK": "1",
|
||||
"SHELLCRASH_ATTACH_NEKO": "auto",
|
||||
"SHELLCRASH_ATTACH_FFMPEG": "auto",
|
||||
@ -92,12 +94,12 @@ def select_shellcrash_node() -> None:
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
f"http://127.0.0.1:9999/proxies/{urllib.parse.quote(group)}",
|
||||
data=json.dumps({"name": TUIC3}).encode(),
|
||||
data=json.dumps({"name": SHELLCRASH_PUSH_NODE}).encode(),
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="PUT",
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=8) as resp:
|
||||
print(f"[ok] shellcrash {group} -> {TUIC3} ({resp.status})")
|
||||
print(f"[ok] shellcrash {group} -> {SHELLCRASH_PUSH_NODE} ({resp.status})")
|
||||
except Exception as exc:
|
||||
print(f"[warn] shellcrash {group}: {exc}")
|
||||
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
@ -12,11 +13,25 @@ ROOT = Path(__file__).resolve().parent.parent
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from src.neko_docker_host import ( # noqa: E402
|
||||
neko_extra_hosts_mapping,
|
||||
sanitize_docker_host_ip,
|
||||
sanitize_neko_browser_proxy,
|
||||
)
|
||||
|
||||
def _load_neko_docker_host_helpers():
|
||||
# Keep this renderer usable from Linux service scripts with system Python.
|
||||
# Importing src.neko_docker_host normally executes src/__init__.py, which
|
||||
# pulls app dependencies that are not required for compose rendering.
|
||||
module_path = ROOT / "src" / "neko_docker_host.py"
|
||||
spec = importlib.util.spec_from_file_location("_neko_docker_host_standalone", module_path)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError(f"Unable to load {module_path}")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
_neko_docker_host = _load_neko_docker_host_helpers()
|
||||
build_neko_browser_proxy_url = _neko_docker_host.build_neko_browser_proxy_url
|
||||
neko_extra_hosts_mapping = _neko_docker_host.neko_extra_hosts_mapping
|
||||
sanitize_docker_host_ip = _neko_docker_host.sanitize_docker_host_ip
|
||||
sanitize_neko_browser_proxy = _neko_docker_host.sanitize_neko_browser_proxy
|
||||
|
||||
|
||||
def env(name: str, default: str) -> str:
|
||||
@ -90,6 +105,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")
|
||||
tz = env("TZ", "America/Chicago")
|
||||
host_asset_dir = env("NEKO_HOST_ASSET_DIR", ".")
|
||||
base_profile = env("NEKO_PROFILE_HOST_DIR", str(Path.cwd() / "data" / "chromium-profile-v2"))
|
||||
http_base = int(env("NEKO_HTTP_PORT", "9200"))
|
||||
@ -132,6 +148,7 @@ def render(count: int) -> str:
|
||||
f" {extra_hosts_line.strip()}",
|
||||
f" container_name: live-neko-{idx}",
|
||||
" environment:",
|
||||
f" TZ: {q(tz)}",
|
||||
f" DISPLAY: {q(display)}",
|
||||
f" ENV_DISPLAY: {q(display)}",
|
||||
f" ENV_USER: {q(container_user)}",
|
||||
@ -167,6 +184,7 @@ def render(count: int) -> str:
|
||||
f" - {q(f'{udp_mux}:{udp_mux}/udp')}",
|
||||
f" - {q(f'{udp_range}:{udp_range}/udp')}",
|
||||
" volumes:",
|
||||
' - "/etc/localtime:/etc/localtime:ro"',
|
||||
f" - {q(f'{profile}:/home/neko/.config/chromium')}",
|
||||
f" - {q(f'{profile}:/home/neko/.config/google-chrome')}",
|
||||
f" - {q(f'{policy_dir}:/etc/chromium/policies/managed:ro')}",
|
||||
|
||||
@ -40,6 +40,9 @@ def main() -> int:
|
||||
"hide_event_hub": run(
|
||||
ssh, f"grep -c 'HIDE_YOUTUBE_LIVE_EVENT_HUB = true' {BASE}/web-console/components/live-product/LiveYoutubeUnmannedView.tsx"
|
||||
).strip(),
|
||||
"hide_quality_guard": run(
|
||||
ssh, f"grep -c 'HIDE_YOUTUBE_QUALITY_GUARD = true' {BASE}/web-console/components/live-product/LiveYoutubeUnmannedView.tsx"
|
||||
).strip(),
|
||||
"static_chunk": run(
|
||||
ssh, f"ls {BASE}/web-console/out/_next/static/chunks/904-*.js 2>/dev/null | tail -1"
|
||||
).strip(),
|
||||
@ -68,6 +71,7 @@ def main() -> int:
|
||||
"ok" in checks["health"]
|
||||
and checks["hide_relay_snapshot"] == "1"
|
||||
and checks["hide_event_hub"] == "1"
|
||||
and checks["hide_quality_guard"] == "1"
|
||||
and checks["proxychains_fn"] == "1"
|
||||
)
|
||||
emit(f"\nDEPLOY_TEST: {'PASS' if ok else 'PARTIAL'}")
|
||||
|
||||
@ -222,6 +222,23 @@ type SerialPortInfo = {
|
||||
name?: string;
|
||||
};
|
||||
|
||||
type StudioOpsPlaybook = {
|
||||
id?: string;
|
||||
title?: string;
|
||||
category?: string;
|
||||
priority?: string;
|
||||
description?: string;
|
||||
services?: string[];
|
||||
dependencies?: Array<{ service_id?: string; label?: string; available?: boolean; running?: boolean; status?: string; detail?: string }>;
|
||||
required_count?: number;
|
||||
running_count?: number;
|
||||
available_count?: number;
|
||||
ready?: boolean;
|
||||
actions?: Array<{ service?: string; action?: string; label?: string }>;
|
||||
snapshot?: boolean;
|
||||
status?: string;
|
||||
};
|
||||
|
||||
type StudioOpsSummary = {
|
||||
doctor?: {
|
||||
score?: number;
|
||||
@ -240,6 +257,7 @@ type StudioOpsSummary = {
|
||||
video?: Array<{ path?: string; label?: string; name?: string }>;
|
||||
updated_at?: number;
|
||||
};
|
||||
playbooks?: StudioOpsPlaybook[];
|
||||
recipes?: Array<{ id?: string; title?: string; category?: string; priority?: string; status?: string; trigger?: string; actions?: string[] }>;
|
||||
apps?: Array<{ id?: string; title?: string; category?: string; priority?: string; installed?: boolean; status?: string; description?: string }>;
|
||||
backups?: { snapshots?: Array<{ id?: string; name?: string; size?: number; created_at?: number; included?: number; skipped?: number }> };
|
||||
@ -821,6 +839,7 @@ export default function LiveControlApp() {
|
||||
() => ["homeassistant", "frigate", "ntfy", "wol"].map((id) => serviceById.get(id)).filter(Boolean) as NonNullable<HubDashboard["services"]>,
|
||||
[serviceById],
|
||||
);
|
||||
const studioPlaybooks = studioOps?.playbooks || [];
|
||||
const wolService = serviceById.get("wol");
|
||||
const nekoLinks = useMemo<NekoBrowserLink[]>(() => extractNekoBrowserLinks(ql), [ql]);
|
||||
const nekoPortsLabel = useMemo(() => formatNekoPorts(nekoLinks), [nekoLinks]);
|
||||
@ -1161,6 +1180,33 @@ export default function LiveControlApp() {
|
||||
}
|
||||
};
|
||||
|
||||
const runStudioPlaybook = async (playbookId?: string) => {
|
||||
const id = (playbookId || "").trim();
|
||||
if (!id) return;
|
||||
setBusy(`studio:playbook:${id}`);
|
||||
try {
|
||||
const data = await fetchJson<{
|
||||
message?: string;
|
||||
failed?: number;
|
||||
summary?: StudioOpsSummary;
|
||||
actions?: Array<{ service_id?: string; action?: string; status?: string; message?: string }>;
|
||||
}>("/studio/ops/playbook", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ playbook_id: id }),
|
||||
});
|
||||
if (data.summary) setStudioOps(data.summary);
|
||||
else await refreshStudioOps(false);
|
||||
await refreshDashboard();
|
||||
const failed = data.failed ?? (data.actions || []).filter((item) => item.status === "error").length;
|
||||
notify(data.message || (failed ? t("场景执行完成,但存在失败步骤", "Playbook completed with failed steps") : t("场景执行完成", "Playbook completed")));
|
||||
} catch (e) {
|
||||
notify((e as Error).message);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (view !== "studio") return;
|
||||
void refreshWolDevices(true);
|
||||
@ -1730,6 +1776,87 @@ export default function LiveControlApp() {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 lg:grid-cols-2 xl:grid-cols-3">
|
||||
{studioPlaybooks.map((playbook) => {
|
||||
const playbookId = playbook.id || "";
|
||||
const playbookBusy = busy === `studio:playbook:${playbookId}`;
|
||||
const dependencies = playbook.dependencies || (playbook.services || []).map((serviceId) => {
|
||||
const svc = serviceById.get(serviceId);
|
||||
return { service_id: serviceId, label: svc?.label || serviceId, running: !!svc?.running, available: svc?.available !== false, status: svc?.status || "unknown", detail: svc?.detail || "" };
|
||||
});
|
||||
const requiredCount = playbook.required_count ?? dependencies.length;
|
||||
const runningCount = playbook.running_count ?? dependencies.filter((item) => item.running).length;
|
||||
return (
|
||||
<motion.div
|
||||
key={playbookId || playbook.title}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className={`rounded-2xl border p-5 shadow-xl ${
|
||||
portalTheme === "light" ? "border-sky-200/80 bg-white shadow-sky-100/40" : "border-sky-400/15 bg-zinc-950/55 shadow-black/30"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h3 className={`flex items-center gap-2 text-sm font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
|
||||
<Route className={`h-4 w-4 ${portalTheme === "light" ? "text-sky-700" : "text-sky-300"}`} />
|
||||
<span className="line-clamp-1">{playbook.title || playbookId}</span>
|
||||
</h3>
|
||||
<p className={`mt-2 line-clamp-2 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
|
||||
{playbook.description || playbook.category || "Playbook"}
|
||||
</p>
|
||||
</div>
|
||||
<span className={`shrink-0 rounded-full px-2.5 py-1 text-[10px] font-semibold ${statusPill(playbook.status || "ready")}`}>
|
||||
{runningCount}/{requiredCount || 0}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-4 flex flex-wrap gap-1.5">
|
||||
{dependencies.map((dependency) => {
|
||||
const serviceId = dependency.service_id || "";
|
||||
return (
|
||||
<span
|
||||
key={serviceId}
|
||||
className={`rounded-full px-2 py-1 text-[10px] font-semibold ${
|
||||
dependency.running
|
||||
? "bg-emerald-500/15 text-emerald-200 ring-1 ring-emerald-400/25"
|
||||
: dependency.available === false
|
||||
? "bg-rose-500/15 text-rose-200 ring-1 ring-rose-400/25"
|
||||
: portalTheme === "light"
|
||||
? "bg-slate-100 text-slate-700 ring-1 ring-slate-200"
|
||||
: "bg-white/5 text-zinc-300 ring-1 ring-white/10"
|
||||
}`}
|
||||
>
|
||||
{serviceId || dependency.label || "service"}:{dependency.running ? "on" : dependency.available === false ? "off" : dependency.status || "idle"}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="mt-4 space-y-2">
|
||||
{(playbook.actions || []).slice(0, 4).map((step, idx) => (
|
||||
<div
|
||||
key={`${step.service || "service"}:${step.action || "action"}:${idx}`}
|
||||
className={`flex items-center justify-between gap-3 rounded-lg border px-3 py-2 text-[11px] ${
|
||||
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-700" : "border-white/10 bg-black/30 text-zinc-300"
|
||||
}`}
|
||||
>
|
||||
<span className="min-w-0 truncate">{step.label || step.service || "service"}</span>
|
||||
<span className="shrink-0 font-mono uppercase">{step.action || "run"}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!!busy || !playbookId}
|
||||
onClick={() => void runStudioPlaybook(playbookId)}
|
||||
className="mt-5 inline-flex w-full items-center justify-center gap-2 rounded-lg bg-sky-500/18 px-3 py-2.5 text-xs font-semibold text-sky-100 ring-1 ring-sky-400/30 transition hover:bg-sky-500/28 disabled:opacity-40"
|
||||
>
|
||||
{playbookBusy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <CirclePlay className="h-3.5 w-3.5" />}
|
||||
{t("鎵ц鍦烘櫙", "Run playbook")}
|
||||
</button>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 xl:grid-cols-4">
|
||||
{[
|
||||
{
|
||||
|
||||
@ -55,6 +55,7 @@ function statusLine(t: TFn, raw: string | undefined): string {
|
||||
const s = (raw || "unknown").toLowerCase();
|
||||
if (s === "online" || s === "running") return t("运行中(PM2/进程在线)", "Running (process online)");
|
||||
if (s === "stopped" || s === "stopping") return t("已停止", "Stopped");
|
||||
if (s === "configured") return t("已配置(未启动)", "Configured (not running)");
|
||||
if (s === "not_found" || s === "errored") return t("未运行或未找到", "Not running / not found");
|
||||
if (s === "invalid") return t("无效进程名", "Invalid process");
|
||||
return raw || "—";
|
||||
@ -88,8 +89,11 @@ type Props = {
|
||||
|
||||
function businessLine(t: TFn, raw: string | undefined, note: string | undefined): string {
|
||||
const s = (raw || "").toLowerCase();
|
||||
if (s === "ready" || s === "configured") return t("已配置,等待启动", "Configured and ready to start");
|
||||
if (s === "inactive") return t("未运行", "Inactive");
|
||||
if (s === "streaming") return t("正在推流到 YouTube", "Pushing to YouTube");
|
||||
if (s === "relay_slow") return t("推流速度偏低", "Relay running slowly");
|
||||
if (s === "relay_starting") return t("转推 Worker 启动中,等待 FFmpeg 进度", "Relay worker starting; waiting for FFmpeg progress");
|
||||
if (s === "waiting_source") return t("等待上游直播源开播", "Waiting for the upstream live source");
|
||||
if (s === "source_live")
|
||||
return t("源站已开播,转推 Worker 未启动", "Source live detected, but no active FFmpeg relay worker");
|
||||
@ -110,8 +114,11 @@ function businessLine(t: TFn, raw: string | undefined, note: string | undefined)
|
||||
function businessShortLine(t: TFn, raw: string | undefined, pushing = false): string {
|
||||
if (pushing) return t("推流中", "Pushing");
|
||||
const s = (raw || "").toLowerCase();
|
||||
if (s === "ready" || s === "configured") return t("已配置", "Ready");
|
||||
if (s === "inactive") return t("未运行", "Inactive");
|
||||
if (s === "streaming") return t("推流中", "Pushing");
|
||||
if (s === "relay_slow") return t("低速", "Slow");
|
||||
if (s === "relay_starting") return t("启动中", "Starting");
|
||||
if (s === "waiting_source") return t("等源", "Wait source");
|
||||
if (s === "source_live") return t("源开播", "Source live");
|
||||
if (s === "monitoring") return t("监控中", "Monitoring");
|
||||
@ -125,8 +132,9 @@ function businessShortLine(t: TFn, raw: string | undefined, pushing = false): st
|
||||
|
||||
function businessBadgeClass(raw: string | undefined): string {
|
||||
const s = (raw || "").trim().toLowerCase();
|
||||
if (s === "ready" || s === "configured") return "bg-sky-500/15 text-sky-100 ring-sky-500/25";
|
||||
if (s === "streaming" || s === "relay_slow") return "bg-emerald-500/15 text-emerald-200 ring-emerald-500/30";
|
||||
if (s === "waiting_source" || s === "monitoring" || s === "source_live") {
|
||||
if (s === "waiting_source" || s === "monitoring" || s === "source_live" || s === "relay_starting") {
|
||||
return "bg-amber-500/15 text-amber-100 ring-amber-500/25";
|
||||
}
|
||||
if (s === "misconfigured" || s === "youtube_key_rejected" || s === "error" || s === "stale" || s === "source_stalled") {
|
||||
@ -187,13 +195,11 @@ export function LiveProcessLiveLogCard({
|
||||
const requestSeqRef = useRef(0);
|
||||
|
||||
const douyinHints = extractDouyinRoomHints(urlListText);
|
||||
const onlineNow = /^(online|running)$/i.test(processStatus);
|
||||
const roomFromLog = extractDouyinCurrentRoomFromLog(recentLog);
|
||||
const fallbackUrls = extractDouyinLiveUrls(urlListText);
|
||||
const fallbackUrl = fallbackUrls[0] ?? "";
|
||||
const pushingNow =
|
||||
isPushing ||
|
||||
!!monitorRow?.is_pushing ||
|
||||
["streaming", "relay_slow"].includes(businessStatus.trim().toLowerCase());
|
||||
const liveMetrics = mergeFfmpegMetrics(
|
||||
{
|
||||
@ -212,11 +218,11 @@ export function LiveProcessLiveLogCard({
|
||||
? fmtDuration(Math.max(0, Math.floor(statusFfmpegTime)))
|
||||
: null;
|
||||
const liveStatsText = formatFfmpegStatsBrief(liveMetrics, {
|
||||
live: pushingNow || onlineNow || !!monitorRow?.ffmpeg_active,
|
||||
live: pushingNow,
|
||||
});
|
||||
const ffmpegWorkerLabel = ffmpegPids.length
|
||||
? ffmpegPids.join(", ")
|
||||
: pushingNow || monitorRow?.ffmpeg_active
|
||||
: pushingNow
|
||||
? t("转推活跃(PID 未采集)", "Relay active (PID n/a)")
|
||||
: t("无", "none");
|
||||
const suppressAmbiguousBackend = sourceAmbiguous && pushingNow && !sourceCurrent;
|
||||
@ -596,7 +602,7 @@ export function LiveProcessLiveLogCard({
|
||||
<span className="text-[11px] font-medium text-zinc-400">
|
||||
{roomFromLog
|
||||
? t("当前直播源站(日志)", "Current source (from log)")
|
||||
: onlineNow
|
||||
: pushingNow
|
||||
? t("配置中的源站地址", "Configured source URL")
|
||||
: t("源站快捷入口", "Source quick link")}
|
||||
</span>
|
||||
|
||||
@ -181,6 +181,9 @@ const HIDE_YOUTUBE_MULTI_PRO_TOGGLE = false;
|
||||
/** UI 隐藏顶部「转播实况」概览卡(状态、指标网格、打开源站等) */
|
||||
const HIDE_YOUTUBE_RELAY_SNAPSHOT = true;
|
||||
|
||||
/** UI 隐藏「算法友好质量守护」板块 */
|
||||
const HIDE_YOUTUBE_QUALITY_GUARD = true;
|
||||
|
||||
/** UI 隐藏「直播事件中枢」板块 */
|
||||
const HIDE_YOUTUBE_LIVE_EVENT_HUB = true;
|
||||
|
||||
@ -214,7 +217,7 @@ function isLivePushingRow(row?: LiveProcRow): boolean {
|
||||
!!row?.is_pushing ||
|
||||
business === "streaming" ||
|
||||
business === "relay_slow" ||
|
||||
(business === "source_stalled" && !!row?.ffmpeg_active)
|
||||
business === "source_stalled"
|
||||
);
|
||||
}
|
||||
|
||||
@ -416,6 +419,7 @@ function businessStatusLabel(row: LiveProcRow | undefined, t: TFn): string {
|
||||
if (business === "streaming") return t("推流中", "Pushing");
|
||||
if (business === "source_stalled") return t("源卡住", "Source stalled");
|
||||
if (business === "relay_slow") return t("低速推流", "Relay slow");
|
||||
if (business === "relay_starting") return t("转推启动中", "Relay starting");
|
||||
if (business === "waiting_source") return t("等待上游", "Waiting source");
|
||||
if (business === "source_live") return t("源已开播,转推未起", "Source live, relay down");
|
||||
if (business === "monitoring") return t("监控中", "Monitoring");
|
||||
@ -433,14 +437,14 @@ function businessStatusBadgeClass(row: LiveProcRow | undefined): string {
|
||||
if (business === "streaming") return "bg-emerald-500/15 text-emerald-200 ring-emerald-500/30";
|
||||
if (business === "relay_slow") return "bg-amber-500/15 text-amber-100 ring-amber-500/25";
|
||||
if (business === "source_stalled") return "bg-rose-500/15 text-rose-100 ring-rose-500/25";
|
||||
if (business === "waiting_source" || business === "monitoring") {
|
||||
if (business === "waiting_source" || business === "monitoring" || business === "relay_starting") {
|
||||
return "bg-amber-500/15 text-amber-100 ring-amber-500/25";
|
||||
}
|
||||
if (business === "source_live") return "bg-sky-500/15 text-sky-100 ring-sky-500/25";
|
||||
if (business === "misconfigured" || business === "youtube_key_rejected" || business === "error" || business === "stale") {
|
||||
return "bg-rose-500/15 text-rose-100 ring-rose-500/25";
|
||||
}
|
||||
if (pm2StatusOnline(row?.process_status)) return "bg-emerald-500/15 text-emerald-200 ring-emerald-500/30";
|
||||
if (pm2StatusOnline(row?.process_status)) return "bg-zinc-500/15 text-zinc-200 ring-zinc-500/25";
|
||||
return "bg-zinc-600/20 text-zinc-400 ring-zinc-500/25";
|
||||
}
|
||||
|
||||
@ -558,16 +562,12 @@ function qualityPillClass(level?: string): string {
|
||||
return "bg-cyan-500/15 text-cyan-100 ring-cyan-500/25";
|
||||
}
|
||||
|
||||
function metricText(value: number | undefined, suffix = ""): string {
|
||||
if (typeof value !== "number" || Number.isNaN(value)) return "-";
|
||||
return `${value.toFixed(value >= 100 ? 0 : 2).replace(/\.00$/, "")}${suffix}`;
|
||||
}
|
||||
|
||||
function laneStatusEmoji(row?: LiveProcRow): string {
|
||||
const business = (row?.business_status || "").trim().toLowerCase();
|
||||
if (business === "streaming") return "🟢";
|
||||
if (business === "relay_slow") return "🟡";
|
||||
if (business === "source_stalled") return "🟠";
|
||||
if (business === "relay_starting") return "🔵";
|
||||
if (business === "youtube_key_rejected" || business === "error") return "🔴";
|
||||
if (business === "source_live") return "🔵";
|
||||
if (business === "waiting_source") return "⚪";
|
||||
@ -1582,24 +1582,6 @@ export function LiveYoutubeUnmannedView({
|
||||
],
|
||||
);
|
||||
|
||||
const saveProLaneSettings = useCallback(async () => {
|
||||
if (!active) return;
|
||||
setLaneSaving(true);
|
||||
setLaneStatus(null);
|
||||
try {
|
||||
const saved = await persistActiveLaneDraft();
|
||||
currentProcRef.current = saved.pm2;
|
||||
setCurrentProc(saved.pm2);
|
||||
setLaneStatus(t("线路设置已保存", "Lane settings saved"));
|
||||
} catch (e) {
|
||||
const message = (e as Error).message;
|
||||
setLaneStatus(message);
|
||||
notify(message);
|
||||
} finally {
|
||||
setLaneSaving(false);
|
||||
}
|
||||
}, [active, notify, persistActiveLaneDraft, setCurrentProc, t]);
|
||||
|
||||
const saveYoutubeIniToServer = async (content: string, processPm2 = currentProcRef.current) => {
|
||||
const targetPm2 = processPm2.trim();
|
||||
if (!targetPm2) {
|
||||
@ -1626,6 +1608,43 @@ export function LiveYoutubeUnmannedView({
|
||||
}
|
||||
};
|
||||
|
||||
const saveProLaneSettings = useCallback(async () => {
|
||||
if (!active) return;
|
||||
setLaneSaving(true);
|
||||
setLaneStatus(null);
|
||||
try {
|
||||
const saved = await persistActiveLaneDraft();
|
||||
currentProcRef.current = saved.pm2;
|
||||
setCurrentProc(saved.pm2);
|
||||
const base = parseYoutubeIniFields(youtubeIniText || buildYoutubeIniFromFields(ytFields));
|
||||
const draft = laneDrafts[active.id] ?? laneDraftFromChannel(active);
|
||||
const body = buildYoutubeIniFromFields({
|
||||
key: (draft.streamKey || activeLaneValidation.normalizedStreamKey || "").trim(),
|
||||
rtmps: base.rtmps,
|
||||
bitrate: base.bitrate,
|
||||
fastAudio: base.fastAudio,
|
||||
});
|
||||
await saveYoutubeIniToServer(body, saved.pm2);
|
||||
setLaneStatus(t("线路设置与推流配置已保存", "Lane settings and stream config saved"));
|
||||
} catch (e) {
|
||||
const message = (e as Error).message;
|
||||
setLaneStatus(message);
|
||||
notify(message);
|
||||
} finally {
|
||||
setLaneSaving(false);
|
||||
}
|
||||
}, [
|
||||
active,
|
||||
activeLaneValidation.normalizedStreamKey,
|
||||
laneDrafts,
|
||||
notify,
|
||||
persistActiveLaneDraft,
|
||||
setCurrentProc,
|
||||
t,
|
||||
youtubeIniText,
|
||||
ytFields,
|
||||
]);
|
||||
|
||||
const applyFieldsAndSave = async () => {
|
||||
const body = buildYoutubeIniFromFields(ytFields);
|
||||
await saveYoutubeIniToServer(body);
|
||||
@ -2040,7 +2059,6 @@ export function LiveYoutubeUnmannedView({
|
||||
const overviewStatusLabel = proLaneStatusLabel(overviewRow, t);
|
||||
const overviewSourceUrl = douyinSourceUrlFor(overviewRow, monitorUrlDraft);
|
||||
const overviewQualityLane = qualityGuard?.lanes?.find((lane) => lane.process === runtimeLogProc);
|
||||
const overviewQualityMetrics = overviewQualityLane?.metrics;
|
||||
const overviewLiveMetrics = qualityLaneMetrics(overviewRow, overviewQualityLane);
|
||||
const overviewQualityScore = overviewQualityLane?.score ?? null;
|
||||
const overviewPushingLanes =
|
||||
@ -3208,7 +3226,7 @@ export function LiveYoutubeUnmannedView({
|
||||
const laneStatusLabel = proLaneStatusLabel(row, t);
|
||||
const laneLiveMetrics = qualityLaneMetrics(row, laneQuality);
|
||||
const laneStatsText = formatFfmpegStatsBrief(laneLiveMetrics, {
|
||||
live: laneLiveMetrics.live || rowOnline || isLivePushingRow(row),
|
||||
live: laneLiveMetrics.live || isLivePushingRow(row),
|
||||
});
|
||||
return (
|
||||
<div
|
||||
@ -3385,7 +3403,7 @@ export function LiveYoutubeUnmannedView({
|
||||
preferredTitle={mode === "pro" ? overviewLaneName : undefined}
|
||||
/>
|
||||
|
||||
{qualityGuardPanel}
|
||||
{!HIDE_YOUTUBE_QUALITY_GUARD ? qualityGuardPanel : null}
|
||||
|
||||
{!HIDE_YOUTUBE_LIVE_EVENT_HUB ? humanLiveEventPanel || liveEventPanel : null}
|
||||
|
||||
|
||||
109
d2ypp2/web-console/lib/adaptivePoll.ts
Normal file
109
d2ypp2/web-console/lib/adaptivePoll.ts
Normal file
@ -0,0 +1,109 @@
|
||||
/** Adaptive polling intervals for live-console views (reduce load when idle or hidden). */
|
||||
|
||||
export type MonitorActivity = "hot" | "warm" | "idle";
|
||||
|
||||
type RowLike = {
|
||||
process_status?: string;
|
||||
business_status?: string;
|
||||
is_pushing?: boolean;
|
||||
};
|
||||
|
||||
const HOT_BUSINESS = new Set([
|
||||
"streaming",
|
||||
"relay_slow",
|
||||
"source_live",
|
||||
"source_stalled",
|
||||
"youtube_key_rejected",
|
||||
"error",
|
||||
]);
|
||||
|
||||
const WARM_BUSINESS = new Set(["waiting_source", "monitoring", "misconfigured", "stale"]);
|
||||
WARM_BUSINESS.add("relay_starting");
|
||||
|
||||
function pm2Online(status?: string): boolean {
|
||||
return /^(online|running)$/i.test((status || "").trim());
|
||||
}
|
||||
|
||||
export function classifyRowActivity(row?: RowLike): MonitorActivity {
|
||||
if (!row) return "idle";
|
||||
const business = (row.business_status || "").trim().toLowerCase();
|
||||
if (row.is_pushing || HOT_BUSINESS.has(business)) return "hot";
|
||||
if (WARM_BUSINESS.has(business) || pm2Online(row.process_status)) return "warm";
|
||||
return "idle";
|
||||
}
|
||||
|
||||
export function classifyProcessMonitorActivity(rows: RowLike[]): MonitorActivity {
|
||||
let activity: MonitorActivity = "idle";
|
||||
for (const row of rows) {
|
||||
const rowActivity = classifyRowActivity(row);
|
||||
if (rowActivity === "hot") return "hot";
|
||||
if (rowActivity === "warm") activity = "warm";
|
||||
}
|
||||
return activity;
|
||||
}
|
||||
|
||||
/** Background tab: slow heartbeat instead of stopping entirely. */
|
||||
export const HIDDEN_TAB_POLL_MS = 30_000;
|
||||
|
||||
export function processMonitorPollMs(options: {
|
||||
view: string;
|
||||
activity: MonitorActivity;
|
||||
pageVisible: boolean;
|
||||
}): number {
|
||||
if (!options.pageVisible) return HIDDEN_TAB_POLL_MS;
|
||||
if (options.view === "live_youtube" || options.view === "live_tiktok") {
|
||||
switch (options.activity) {
|
||||
case "hot":
|
||||
return 800;
|
||||
case "warm":
|
||||
return 2500;
|
||||
default:
|
||||
return 5000;
|
||||
}
|
||||
}
|
||||
return 4000;
|
||||
}
|
||||
|
||||
export function statusPollMs(options: {
|
||||
activity: MonitorActivity;
|
||||
pageVisible: boolean;
|
||||
paused?: boolean;
|
||||
}): number {
|
||||
if (options.paused) return 0;
|
||||
if (!options.pageVisible) return HIDDEN_TAB_POLL_MS;
|
||||
switch (options.activity) {
|
||||
case "hot":
|
||||
return 800;
|
||||
case "warm":
|
||||
return 2000;
|
||||
default:
|
||||
return 4000;
|
||||
}
|
||||
}
|
||||
|
||||
export function liveEventsPollMs(options: { activeEvents: number; pageVisible: boolean }): number {
|
||||
if (!options.pageVisible) return HIDDEN_TAB_POLL_MS;
|
||||
return options.activeEvents > 0 ? 4000 : 12_000;
|
||||
}
|
||||
|
||||
export function qualityGuardPollMs(options: { pushingLanes: number; pageVisible: boolean }): number {
|
||||
if (!options.pageVisible) return HIDDEN_TAB_POLL_MS;
|
||||
return options.pushingLanes > 0 ? 6000 : 15_000;
|
||||
}
|
||||
|
||||
export function urlConfigPollMs(options: { pageVisible: boolean }): number {
|
||||
if (!options.pageVisible) return 0;
|
||||
return 12_000;
|
||||
}
|
||||
|
||||
export function formatPollBadge(ms: number, t: (zh: string, en: string) => string): string {
|
||||
if (ms <= 0) return t("已暂停", "Paused");
|
||||
if (ms >= 30_000) return t("约 30 秒", "~30s");
|
||||
if (ms >= 15_000) return t("约 15 秒", "~15s");
|
||||
if (ms >= 12_000) return t("约 12 秒", "~12s");
|
||||
if (ms >= 5000) return t("约 5 秒", "~5s");
|
||||
if (ms >= 2500) return t("约 2.5 秒", "~2.5s");
|
||||
if (ms >= 2000) return t("约 2 秒", "~2s");
|
||||
if (ms >= 800) return t("约 1 秒", "~1s");
|
||||
return `${ms}ms`;
|
||||
}
|
||||
54
d2ypp2/web-console/lib/dashboardFormat.ts
Normal file
54
d2ypp2/web-console/lib/dashboardFormat.ts
Normal file
@ -0,0 +1,54 @@
|
||||
export function formatUptime(sec?: number) {
|
||||
if (sec == null || !Number.isFinite(sec)) return "—";
|
||||
const s = Math.max(0, Math.floor(sec));
|
||||
const d = Math.floor(s / 86400);
|
||||
const h = Math.floor((s % 86400) / 3600);
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
if (d > 0) return `${d}d ${h}h`;
|
||||
if (h > 0) return `${h}h ${m}m`;
|
||||
return `${m}m`;
|
||||
}
|
||||
|
||||
export function formatBytes(value?: number) {
|
||||
if (value == null || !Number.isFinite(value)) return "—";
|
||||
if (value === 0) return "0 B";
|
||||
const u = ["B", "KB", "MB", "GB", "TB"];
|
||||
let n = value;
|
||||
let i = 0;
|
||||
while (n >= 1024 && i < u.length - 1) {
|
||||
n /= 1024;
|
||||
i += 1;
|
||||
}
|
||||
return `${n.toFixed(n >= 10 || i === 0 ? 0 : 1)} ${u[i]}`;
|
||||
}
|
||||
|
||||
export function formatRate(value?: number) {
|
||||
const text = formatBytes(value);
|
||||
return text === "—" ? text : `${text}/s`;
|
||||
}
|
||||
|
||||
export function formatPercent(used: number, total: number) {
|
||||
if (!total || !Number.isFinite(used) || !Number.isFinite(total)) return 0;
|
||||
return Math.min(100, Math.max(0, Math.round((used / total) * 100)));
|
||||
}
|
||||
|
||||
export function statusPill(status: string) {
|
||||
if (status === "online" || status === "running" || status === "streaming")
|
||||
return "bg-emerald-500/15 text-emerald-300 ring-1 ring-emerald-500/30";
|
||||
if (status === "configured") return "bg-sky-500/15 text-sky-200 ring-1 ring-sky-500/25";
|
||||
if (status === "skipped") return "bg-slate-500/15 text-slate-300 ring-1 ring-slate-500/30";
|
||||
if (status === "stopped" || status === "not_found")
|
||||
return "bg-zinc-500/15 text-zinc-400 ring-1 ring-zinc-500/25";
|
||||
if (status === "error") return "bg-rose-500/15 text-rose-300 ring-1 ring-rose-500/35";
|
||||
return "bg-violet-500/15 text-violet-200 ring-1 ring-violet-500/30";
|
||||
}
|
||||
|
||||
export function statusLabel(status: string, t: (zh: string, en: string) => string) {
|
||||
const normalized = (status || "").trim().toLowerCase();
|
||||
if (normalized === "online" || normalized === "running" || normalized === "streaming") return t("运行中", "Running");
|
||||
if (normalized === "configured") return t("已配置", "Configured");
|
||||
if (normalized === "not_found") return t("未注册", "Unregistered");
|
||||
if (normalized === "stopped") return t("已停止", "Stopped");
|
||||
if (normalized === "error") return t("异常", "Error");
|
||||
return status || "—";
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
type JsonErrorPayload = {
|
||||
error?: string;
|
||||
message?: string;
|
||||
detail?: string;
|
||||
detail?: unknown;
|
||||
};
|
||||
|
||||
const MAX_ERROR_TEXT = 240;
|
||||
@ -18,6 +18,30 @@ function defaultHttpMessage(response: Response): string {
|
||||
return `HTTP ${response.status}${suffix}`;
|
||||
}
|
||||
|
||||
function stringifyDetail(detail: unknown): string {
|
||||
if (typeof detail === "string") return detail.trim();
|
||||
if (Array.isArray(detail)) {
|
||||
const parts = detail
|
||||
.map((item) => {
|
||||
if (typeof item === "string") return item.trim();
|
||||
if (item && typeof item === "object" && "msg" in item) {
|
||||
return String((item as { msg?: unknown }).msg ?? "").trim();
|
||||
}
|
||||
return "";
|
||||
})
|
||||
.filter(Boolean);
|
||||
return parts.join("; ");
|
||||
}
|
||||
if (detail && typeof detail === "object") {
|
||||
try {
|
||||
return summarizeResponseText(JSON.stringify(detail));
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function extractErrorMessage(
|
||||
response: Response,
|
||||
raw: string,
|
||||
@ -26,13 +50,19 @@ function extractErrorMessage(
|
||||
const candidate =
|
||||
(typeof payload?.error === "string" && payload.error.trim()) ||
|
||||
(typeof payload?.message === "string" && payload.message.trim()) ||
|
||||
(typeof payload?.detail === "string" && payload.detail.trim()) ||
|
||||
stringifyDetail(payload?.detail) ||
|
||||
summarizeResponseText(raw);
|
||||
return candidate || defaultHttpMessage(response);
|
||||
}
|
||||
|
||||
export async function fetchJsonResponse<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(url, { cache: "no-store", ...init });
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(url, { cache: "no-store", ...init });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error && error.message.trim() ? error.message : "Network request failed";
|
||||
throw new Error(`Failed to fetch ${url}: ${message}`);
|
||||
}
|
||||
const raw = await response.text();
|
||||
const trimmed = raw.trim();
|
||||
let payload: (T & JsonErrorPayload) | null = null;
|
||||
@ -60,7 +90,12 @@ export async function fetchJsonResponse<T>(url: string, init?: RequestInit): Pro
|
||||
}
|
||||
|
||||
export async function readErrorMessage(response: Response): Promise<string> {
|
||||
const raw = (await response.text()).trim();
|
||||
let raw = "";
|
||||
try {
|
||||
raw = (await response.text()).trim();
|
||||
} catch {
|
||||
raw = "";
|
||||
}
|
||||
let payload: JsonErrorPayload | null = null;
|
||||
if (raw) {
|
||||
try {
|
||||
|
||||
148
d2ypp2/web-console/lib/ffmpegMetrics.ts
Normal file
148
d2ypp2/web-console/lib/ffmpegMetrics.ts
Normal file
@ -0,0 +1,148 @@
|
||||
export type FfmpegMetrics = {
|
||||
frame?: number;
|
||||
fps?: number;
|
||||
speed?: number;
|
||||
bitrate?: number;
|
||||
drop?: number;
|
||||
dup?: number;
|
||||
};
|
||||
|
||||
type FfmpegMetricKey = keyof FfmpegMetrics;
|
||||
|
||||
type ProcessRowHint = {
|
||||
ffmpeg_speed?: number | null;
|
||||
ffmpeg_frame?: number | null;
|
||||
ffmpeg_active?: boolean;
|
||||
is_pushing?: boolean;
|
||||
ffmpeg_speed_low?: boolean;
|
||||
ffmpeg_progress_stalled?: boolean;
|
||||
};
|
||||
|
||||
const KV_RE = /\b(frame|fps|bitrate|speed|drop|dup)\s*=\s*([^\s]+)/gi;
|
||||
const IDLE_MARKERS = [
|
||||
"等待直播",
|
||||
"waiting",
|
||||
"获取失败",
|
||||
"douyin web api failed",
|
||||
"无录制任务",
|
||||
"网址内容获取失败",
|
||||
"没有正在监测的直播",
|
||||
];
|
||||
|
||||
function parseMetricNumber(value: string, asInt = false): number | undefined {
|
||||
const cleaned = value.replace(/kbits\/s/gi, "").replace(/x$/i, "").trim();
|
||||
const match = cleaned.match(/-?\d+(?:\.\d+)?/);
|
||||
if (!match) return undefined;
|
||||
const parsed = asInt ? parseInt(match[0], 10) : Number(match[0]);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
function lineImpliesRelayIdle(line: string): boolean {
|
||||
const lower = line.toLowerCase();
|
||||
if (lower.includes("frame=") && lower.includes("speed=")) return false;
|
||||
return (
|
||||
IDLE_MARKERS.some((marker) => lower.includes(marker.toLowerCase())) ||
|
||||
lower.includes("error") ||
|
||||
lower.includes("failed")
|
||||
);
|
||||
}
|
||||
|
||||
export function latestFfmpegStatsLine(logText: string, lookback = 12): string {
|
||||
const lines = logText
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean);
|
||||
const tail = lines.slice(-lookback);
|
||||
let statsIdx = -1;
|
||||
let statsLine = "";
|
||||
for (let idx = tail.length - 1; idx >= 0; idx -= 1) {
|
||||
const lower = tail[idx].toLowerCase();
|
||||
if (lower.includes("frame=") && lower.includes("speed=")) {
|
||||
statsIdx = idx;
|
||||
statsLine = tail[idx];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (statsIdx < 0) return "";
|
||||
if (tail.slice(statsIdx + 1).some(lineImpliesRelayIdle)) return "";
|
||||
return statsLine;
|
||||
}
|
||||
|
||||
export function parseFfmpegMetricsFromLog(...texts: string[]): FfmpegMetrics {
|
||||
const raw = texts.filter(Boolean).join("\n");
|
||||
const statsLine = latestFfmpegStatsLine(raw.slice(-16000));
|
||||
const metrics: FfmpegMetrics = {};
|
||||
if (!statsLine) return metrics;
|
||||
KV_RE.lastIndex = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = KV_RE.exec(statsLine)) !== null) {
|
||||
const key = match[1].toLowerCase() as FfmpegMetricKey;
|
||||
const value = match[2];
|
||||
if (key === "frame" || key === "drop" || key === "dup") {
|
||||
const parsed = parseMetricNumber(value, true);
|
||||
if (parsed != null) metrics[key] = parsed;
|
||||
} else if (key === "fps" || key === "speed" || key === "bitrate") {
|
||||
const parsed = parseMetricNumber(value);
|
||||
if (parsed != null) metrics[key] = parsed;
|
||||
}
|
||||
}
|
||||
return metrics;
|
||||
}
|
||||
|
||||
export function mergeFfmpegMetrics(
|
||||
row?: ProcessRowHint,
|
||||
qualityMetrics?: FfmpegMetrics,
|
||||
logText = "",
|
||||
): FfmpegMetrics & { speedLow?: boolean; progressStalled?: boolean; live: boolean } {
|
||||
const fromLog = parseFfmpegMetricsFromLog(logText);
|
||||
const live = !!row?.is_pushing;
|
||||
return {
|
||||
frame: pickNumber(row?.ffmpeg_frame, qualityMetrics?.frame, fromLog.frame),
|
||||
fps: pickNumber(qualityMetrics?.fps, fromLog.fps),
|
||||
speed: pickNumber(row?.ffmpeg_speed, qualityMetrics?.speed, fromLog.speed),
|
||||
bitrate: pickNumber(qualityMetrics?.bitrate, fromLog.bitrate),
|
||||
drop: pickNumber(qualityMetrics?.drop, fromLog.drop),
|
||||
dup: pickNumber(qualityMetrics?.dup, fromLog.dup),
|
||||
speedLow: row?.ffmpeg_speed_low,
|
||||
progressStalled: row?.ffmpeg_progress_stalled,
|
||||
live,
|
||||
};
|
||||
}
|
||||
|
||||
function pickNumber(...values: Array<number | null | undefined>): number | undefined {
|
||||
for (const value of values) {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function formatBitrateLabel(kbps: number | undefined | null): string | null {
|
||||
if (typeof kbps !== "number" || !Number.isFinite(kbps) || kbps <= 0) return null;
|
||||
if (kbps >= 1000) return `${(kbps / 1000).toFixed(1)} Mbps`;
|
||||
return `${Math.round(kbps)} kbps`;
|
||||
}
|
||||
|
||||
export function formatFfmpegMetricValue(
|
||||
value: number | undefined,
|
||||
suffix = "",
|
||||
digits = 2,
|
||||
): string {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) return "—";
|
||||
const text = value >= 100 ? String(Math.round(value)) : value.toFixed(digits).replace(/\.00$/, "");
|
||||
return `${text}${suffix}`;
|
||||
}
|
||||
|
||||
export function formatFfmpegStatsBrief(
|
||||
metrics: FfmpegMetrics,
|
||||
opts?: { live?: boolean },
|
||||
): string {
|
||||
const parts = [
|
||||
`fps ${formatFfmpegMetricValue(metrics.fps)}`,
|
||||
`speed ${formatFfmpegMetricValue(metrics.speed, "x")}`,
|
||||
`frame ${formatFfmpegMetricValue(metrics.frame, "", 0)}`,
|
||||
];
|
||||
const bitrate = formatBitrateLabel(metrics.bitrate);
|
||||
if (bitrate) parts.push(bitrate);
|
||||
if (!opts?.live && parts.every((part) => part.endsWith("—"))) return "";
|
||||
return parts.join(" · ");
|
||||
}
|
||||
@ -1,82 +0,0 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
/**
|
||||
* 仅 `next dev` 生效:把 FastAPI 同名路由代理到本机 uvicorn。
|
||||
* 生产环境由 FastAPI 托管 web-console/out,浏览器与 API 同域,不需要本中间件。
|
||||
*/
|
||||
const TARGET = process.env.API_PROXY_TARGET || "http://127.0.0.1:8001";
|
||||
|
||||
const API_ROOTS = new Set([
|
||||
"process_monitor",
|
||||
"server_info",
|
||||
"health",
|
||||
"status",
|
||||
"start",
|
||||
"stop",
|
||||
"restart",
|
||||
"get_config",
|
||||
"save_config",
|
||||
"get_url_config",
|
||||
"save_url_config",
|
||||
"stack",
|
||||
"service_action",
|
||||
"managed_roots",
|
||||
"managed_files",
|
||||
"managed_file",
|
||||
"deploy",
|
||||
"shellcrash",
|
||||
"hardware_profile",
|
||||
"system_snapshot",
|
||||
"android",
|
||||
"hub",
|
||||
"youtube_pro_channels",
|
||||
"tiktok_replay",
|
||||
]);
|
||||
const SHELLCRASH_API_PATHS = new Set(["/shellcrash/apply_profile", "/shellcrash/web_panel"]);
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
if (process.env.NODE_ENV !== "development") {
|
||||
return NextResponse.next();
|
||||
}
|
||||
const path = request.nextUrl.pathname;
|
||||
const root = path.split("/").filter(Boolean)[0] ?? "";
|
||||
if (root === "shellcrash" && !SHELLCRASH_API_PATHS.has(path)) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
if (!API_ROOTS.has(root)) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
const dest = new URL(path + request.nextUrl.search, TARGET);
|
||||
return NextResponse.rewrite(dest);
|
||||
}
|
||||
|
||||
/** Dev 代理:含 GET/POST 等同名 API(进程与服务控制已优先使用 POST) */
|
||||
export const config = {
|
||||
matcher: [
|
||||
"/process_monitor",
|
||||
"/server_info",
|
||||
"/health",
|
||||
"/status",
|
||||
"/start",
|
||||
"/stop",
|
||||
"/restart",
|
||||
"/get_config",
|
||||
"/save_config",
|
||||
"/get_url_config",
|
||||
"/save_url_config",
|
||||
"/stack/:path*",
|
||||
"/service_action",
|
||||
"/managed_roots",
|
||||
"/managed_files",
|
||||
"/managed_file",
|
||||
"/deploy/:path*",
|
||||
"/shellcrash/:path*",
|
||||
"/hardware_profile",
|
||||
"/system_snapshot",
|
||||
"/android/:path*",
|
||||
"/hub/:path*",
|
||||
"/youtube_pro_channels",
|
||||
"/tiktok_replay/:path*",
|
||||
],
|
||||
};
|
||||
@ -1,10 +1,51 @@
|
||||
const apiTarget = process.env.API_PROXY_TARGET || "http://127.0.0.1:8001";
|
||||
|
||||
const devApiRewrites = [
|
||||
"/process_monitor",
|
||||
"/server_info",
|
||||
"/health",
|
||||
"/status",
|
||||
"/start",
|
||||
"/stop",
|
||||
"/restart",
|
||||
"/get_config",
|
||||
"/save_config",
|
||||
"/get_url_config",
|
||||
"/save_url_config",
|
||||
"/service_action",
|
||||
"/managed_roots",
|
||||
"/managed_files",
|
||||
"/managed_file",
|
||||
"/hardware_profile",
|
||||
"/system_snapshot",
|
||||
"/youtube_pro_channels",
|
||||
"/stack/:path*",
|
||||
"/deploy/:path*",
|
||||
"/android/:path*",
|
||||
"/hub/:path*",
|
||||
"/tiktok_replay/:path*",
|
||||
"/shellcrash/apply_profile",
|
||||
"/shellcrash/web_panel",
|
||||
].map((source) => ({
|
||||
source,
|
||||
destination: `${apiTarget}${source}`,
|
||||
}));
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
output: "export",
|
||||
images: { unoptimized: true },
|
||||
trailingSlash: false,
|
||||
eslint: { ignoreDuringBuilds: true },
|
||||
typescript: { ignoreBuildErrors: true },
|
||||
};
|
||||
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
nextConfig.rewrites = async () => {
|
||||
return {
|
||||
beforeFiles: [],
|
||||
afterFiles: devApiRewrites,
|
||||
fallback: [],
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
self.__BUILD_MANIFEST={__rewrites:{afterFiles:[],beforeFiles:[],fallback:[]},"/_error":["static/chunks/pages/_error-a647cd2c75dc4dc7.js"],sortedPages:["/_app","/_error"]},self.__BUILD_MANIFEST_CB&&self.__BUILD_MANIFEST_CB();
|
||||
@ -1 +0,0 @@
|
||||
self.__BUILD_MANIFEST={__rewrites:{afterFiles:[],beforeFiles:[],fallback:[]},"/_error":["static/chunks/pages/_error-7ba65e1336b92748.js"],sortedPages:["/_app","/_error"]},self.__BUILD_MANIFEST_CB&&self.__BUILD_MANIFEST_CB();
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -1 +1 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[409],{7589:function(e,t,n){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_not-found/page",function(){return n(3634)}])},3634:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return s}}),n(7043);let i=n(7437);n(2265);let o={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"},l={display:"inline-block"},r={display:"inline-block",margin:"0 20px 0 0",padding:"0 23px 0 0",fontSize:24,fontWeight:500,verticalAlign:"top",lineHeight:"49px"},d={fontSize:14,fontWeight:400,lineHeight:"49px",margin:0};function s(){return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("title",{children:"404: This page could not be found."}),(0,i.jsx)("div",{style:o,children:(0,i.jsxs)("div",{children:[(0,i.jsx)("style",{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)}}"}}),(0,i.jsx)("h1",{className:"next-error-h1",style:r,children:"404"}),(0,i.jsx)("div",{style:l,children:(0,i.jsx)("h2",{style:d,children:"This page could not be found."})})]})})]})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)}},function(e){e.O(0,[971,117,744],function(){return e(e.s=7589)}),_N_E=e.O()}]);
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[409],{1763:function(e,t,n){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_not-found/page",function(){return n(1662)}])},1662:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return s}}),n(6651);let i=n(3890);n(8496);let o={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"},l={display:"inline-block"},r={display:"inline-block",margin:"0 20px 0 0",padding:"0 23px 0 0",fontSize:24,fontWeight:500,verticalAlign:"top",lineHeight:"49px"},d={fontSize:14,fontWeight:400,lineHeight:"49px",margin:0};function s(){return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("title",{children:"404: This page could not be found."}),(0,i.jsx)("div",{style:o,children:(0,i.jsxs)("div",{children:[(0,i.jsx)("style",{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)}}"}}),(0,i.jsx)("h1",{className:"next-error-h1",style:r,children:"404"}),(0,i.jsx)("div",{style:l,children:(0,i.jsx)("h2",{style:d,children:"This page could not be found."})})]})})]})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)}},function(e){e.O(0,[649,945,744],function(){return e(e.s=1763)}),_N_E=e.O()}]);
|
||||
@ -1 +0,0 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[357],{4579:function(n,u,e){Promise.resolve().then(e.bind(e,3946))},3946:function(n,u,e){"use strict";e.r(u),e.d(u,{default:function(){return c}});var t=e(7437),r=e(2246);function c(){return(0,t.jsx)(r.d,{})}}},function(n){n.O(0,[500,246,971,117,744],function(){return n(n.s=4579)}),_N_E=n.O()}]);
|
||||
@ -0,0 +1 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[357],{3866:function(n,u,e){Promise.resolve().then(e.bind(e,7588))},7588:function(n,u,e){"use strict";e.r(u),e.d(u,{default:function(){return c}});var t=e(3890),r=e(5653);function c(){return(0,t.jsx)(r.d,{})}}},function(n){n.O(0,[335,653,649,945,744],function(){return n(n.s=3866)}),_N_E=n.O()}]);
|
||||
@ -0,0 +1 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[443],{2476:function(n,u,e){Promise.resolve().then(e.bind(e,8422))},8422:function(n,u,e){"use strict";e.r(u),e.d(u,{default:function(){return c}});var t=e(3890),r=e(5653);function c(){return(0,t.jsx)(r.d,{})}}},function(n){n.O(0,[335,653,649,945,744],function(){return n(n.s=2476)}),_N_E=n.O()}]);
|
||||
@ -1 +0,0 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[443],{6493:function(n,u,e){Promise.resolve().then(e.bind(e,6367))},6367:function(n,u,e){"use strict";e.r(u),e.d(u,{default:function(){return c}});var t=e(7437),r=e(2246);function c(){return(0,t.jsx)(r.d,{})}}},function(n){n.O(0,[500,246,971,117,744],function(){return n(n.s=6493)}),_N_E=n.O()}]);
|
||||
@ -1 +0,0 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{2484:function(e,a,_){Promise.resolve().then(_.t.bind(_,1511,23)),Promise.resolve().then(_.t.bind(_,2221,23)),Promise.resolve().then(_.t.bind(_,7960,23))},7960:function(){},2221:function(e){e.exports={style:{fontFamily:"'__geistMono_c3aa02', '__geistMono_Fallback_c3aa02'"},className:"__className_c3aa02",variable:"__variable_c3aa02"}},1511:function(e){e.exports={style:{fontFamily:"'__geistSans_1e4310', '__geistSans_Fallback_1e4310'"},className:"__className_1e4310",variable:"__variable_1e4310"}}},function(e){e.O(0,[776,971,117,744],function(){return e(e.s=2484)}),_N_E=e.O()}]);
|
||||
@ -0,0 +1 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{7042:function(e,a,_){Promise.resolve().then(_.t.bind(_,2641,23)),Promise.resolve().then(_.t.bind(_,13,23)),Promise.resolve().then(_.t.bind(_,4443,23))},4443:function(){},13:function(e){e.exports={style:{fontFamily:"'__geistMono_c3aa02', '__geistMono_Fallback_c3aa02'"},className:"__className_c3aa02",variable:"__variable_c3aa02"}},2641:function(e){e.exports={style:{fontFamily:"'__geistSans_1e4310', '__geistSans_Fallback_1e4310'"},className:"__className_1e4310",variable:"__variable_1e4310"}}},function(e){e.O(0,[515,649,945,744],function(){return e(e.s=7042)}),_N_E=e.O()}]);
|
||||
@ -1 +0,0 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{2195: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(8904)}},function(n){n.O(0,[500,568,246,904,971,117,744],function(){return n(n.s=2195)}),_N_E=n.O()}]);
|
||||
@ -0,0 +1 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{618:function(n,e,u){Promise.resolve().then(u.bind(u,3372))},3372:function(n,e,u){"use strict";u.r(e),u.d(e,{default:function(){return t.Z}});var t=u(3371)}},function(n){n.O(0,[335,993,653,371,649,945,744],function(){return n(n.s=618)}),_N_E=n.O()}]);
|
||||
@ -1 +0,0 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[6],{3330:function(n,u,e){Promise.resolve().then(e.bind(e,3398))},3398:function(n,u,e){"use strict";e.r(u),e.d(u,{default:function(){return c}});var t=e(7437),r=e(2246);function c(){return(0,t.jsx)(r.d,{})}}},function(n){n.O(0,[500,246,971,117,744],function(){return n(n.s=3330)}),_N_E=n.O()}]);
|
||||
@ -0,0 +1 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[6],{796:function(n,u,e){Promise.resolve().then(e.bind(e,4825))},4825:function(n,u,e){"use strict";e.r(u),e.d(u,{default:function(){return c}});var t=e(3890),r=e(5653);function c(){return(0,t.jsx)(r.d,{})}}},function(n){n.O(0,[335,653,649,945,744],function(){return n(n.s=796)}),_N_E=n.O()}]);
|
||||
@ -0,0 +1 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[851],{6870:function(n,e,u){Promise.resolve().then(u.bind(u,8307))},8307:function(n,e,u){"use strict";u.r(e),u.d(e,{default:function(){return t.Z}});var t=u(3371)}},function(n){n.O(0,[335,993,653,371,649,945,744],function(){return n(n.s=6870)}),_N_E=n.O()}]);
|
||||
@ -1 +0,0 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[851],{8797: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(8904)}},function(n){n.O(0,[500,568,246,904,971,117,744],function(){return n(n.s=8797)}),_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
@ -1 +0,0 @@
|
||||
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[744],{396:function(e,n,t){Promise.resolve().then(t.t.bind(t,2846,23)),Promise.resolve().then(t.t.bind(t,9107,23)),Promise.resolve().then(t.t.bind(t,1060,23)),Promise.resolve().then(t.t.bind(t,4707,23)),Promise.resolve().then(t.t.bind(t,80,23)),Promise.resolve().then(t.t.bind(t,6423,23))}},function(e){var n=function(n){return e(e.s=n)};e.O(0,[971,117],function(){return n(4278),n(396)}),_N_E=e.O()}]);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user