diff --git a/100755 b/100755 new file mode 100644 index 0000000..b914854 --- /dev/null +++ b/100755 @@ -0,0 +1 @@ +Invalid parameter - change diff --git a/d2ypp2/scripts/linux/service_ctl.sh b/d2ypp2/scripts/linux/service_ctl.sh index 891a635..d11b58b 100644 --- a/d2ypp2/scripts/linux/service_ctl.sh +++ b/d2ypp2/scripts/linux/service_ctl.sh @@ -333,6 +333,34 @@ docker_container_status() { docker ps -a --filter "name=^/${name}$" --format '{{.State}}|{{.Status}}' | head -n 1 } +docker_container_env_value() { + local name="$1" key="$2" + if ! have docker; then + return 1 + fi + docker inspect "$name" --format '{{range .Config.Env}}{{println .}}{{end}}' 2>/dev/null | + awk -v key="$key" 'index($0, key "=") == 1 { sub(/^[^=]*=/, ""); print; exit }' +} + +docker_container_force_remove() { + local name="$1" pid + docker rm -f "$name" >/dev/null 2>&1 && return 0 + pid="$(docker inspect -f '{{.State.Pid}}' "$name" 2>/dev/null || true)" + docker update --restart=no "$name" >/dev/null 2>&1 || true + case "$pid" in + ""|0|*[!0-9]*) + ;; + *) + kill -TERM "$pid" 2>/dev/null || true + sleep 2 + if kill -0 "$pid" 2>/dev/null; then + kill -KILL "$pid" 2>/dev/null || true + fi + ;; + esac + docker rm -f "$name" >/dev/null +} + resolve_neko_image() { if [ -n "${NEKO_IMAGE:-}" ]; then printf '%s' "$NEKO_IMAGE" @@ -699,6 +727,21 @@ remove_legacy_neko_container() { fi } +remove_neko_recreate_conflicts() { + local count="${1:-}" idx name + [ -n "$count" ] || count="$(resolve_neko_instance_count)" + have docker || return 0 + for idx in $(seq 1 "$count"); do + name="live-neko-$idx" + docker ps -a --format '{{.Names}}' 2>/dev/null | + awk -v name="$name" '$0 == name || $0 ~ "^[0-9a-f]+_" name "$" { print }' | + while read -r conflict; do + [ -n "$conflict" ] || continue + docker_container_force_remove "$conflict" + done + done +} + is_physical_lan_iface_name() { local name="${1:-}" case "$name" in @@ -1813,15 +1856,25 @@ service_neko_status() { return 0 fi kv available 1 - local state browser_proxy + local state browser_proxy status_value target_nat1to1 runtime_nat1to1 local running_count=0 total_count=0 states="" name instance_count idx ports="" profiles="" + local reconfigure_needed=0 nat_mismatches="" reconfigure_detail="" instance_count="$(resolve_neko_instance_count)" total_count="$instance_count" + if ! neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then + NEKO_WEBRTC_NAT1TO1="$(detect_preferred_lan_ip || true)" + fi + target_nat1to1="${NEKO_WEBRTC_NAT1TO1:-}" for idx in $(seq 1 "$instance_count"); do name="live-neko-$idx" state="$(docker_container_status "$name" || true)" if echo "$state" | grep -qi running; then running_count=$((running_count + 1)) + runtime_nat1to1="$(docker_container_env_value "$name" NEKO_WEBRTC_NAT1TO1 || true)" + if [ -n "$target_nat1to1" ] && [ "$runtime_nat1to1" != "$target_nat1to1" ]; then + reconfigure_needed=1 + nat_mismatches="${nat_mismatches}${name}:${runtime_nat1to1:-unset}->${target_nat1to1}," + fi fi states="${states}${name}:${state:-missing};" ports="${ports}$(resolve_neko_http_port_for_instance "$idx")," @@ -1835,14 +1888,22 @@ service_neko_status() { states="live-neko-chromium:${state};" fi fi + if [ "$running_count" -ge "$total_count" ]; then + status_value=online + elif [ "$running_count" -gt 0 ]; then + status_value=degraded + else + status_value=stopped + fi + if [ "$reconfigure_needed" = "1" ] && [ "$running_count" -gt 0 ]; then + status_value=degraded + reconfigure_detail="; needs_reconfigure=1; runtime_nat1to1_mismatch=${nat_mismatches%,}" + fi kv running "$([ "$running_count" -ge 1 ] && echo 1 || echo 0)" - kv status "$([ "$running_count" -ge "$total_count" ] && echo online || ([ "$running_count" -gt 0 ] && echo degraded || echo stopped))" + kv status "$status_value" kv host "${HOSTNAME_ALIAS}.local" kv port "$NEKO_HTTP_PORT_1" kv url "http://${HOSTNAME_ALIAS}.local:${NEKO_HTTP_PORT_1}" - if ! neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then - NEKO_WEBRTC_NAT1TO1="$(detect_preferred_lan_ip || true)" - fi browser_proxy="${NEKO_BROWSER_PROXY:-}" if [ -z "$browser_proxy" ]; then case "$SHELLCRASH_ATTACH_NEKO" in @@ -1850,7 +1911,7 @@ service_neko_status() { *) browser_proxy=auto ;; esac fi - kv detail "image=$(resolve_neko_image); supervisor_conf=$(resolve_neko_supervisor_conf); start_url=${NEKO_START_URL}; nat1to1=${NEKO_WEBRTC_NAT1TO1:-unset}; instances=${running_count}/${total_count}; ports=${ports%,}; profiles=${profiles%,}; screen=${NEKO_DESKTOP_SCREEN}; shm=${NEKO_SHM_SIZE}; fps=${NEKO_MAX_FPS}; bitrate=${NEKO_VIDEO_BITRATE}; render=${NEKO_BROWSER_RENDER_MODE}; proxy=${browser_proxy}; containers=${states}" + kv detail "image=$(resolve_neko_image); supervisor_conf=$(resolve_neko_supervisor_conf); start_url=${NEKO_START_URL}; nat1to1=${target_nat1to1:-unset}; instances=${running_count}/${total_count}; ports=${ports%,}; profiles=${profiles%,}; screen=${NEKO_DESKTOP_SCREEN}; shm=${NEKO_SHM_SIZE}; fps=${NEKO_MAX_FPS}; bitrate=${NEKO_VIDEO_BITRATE}; render=${NEKO_BROWSER_RENDER_MODE}; proxy=${browser_proxy}${reconfigure_detail}; containers=${states}" } service_neko_start() { @@ -1906,12 +1967,17 @@ service_neko_reconfigure() { service_names="${service_names} neko${idx}" done compose_file="$(render_neko_compose_file)" + remove_neko_recreate_conflicts "$instance_count" # Recreate containers so WebRTC env changes take effect; profile volumes are left untouched. # shellcheck disable=SC2086 compose_in_service_dir "$compose_file" up -d --force-recreate $service_names kv message "Neko WebRTC config reapplied (${instance_count} browser instances)" } +service_neko_restart() { + service_neko_reconfigure +} + export_neko_env() { export NEKO_HTTP_PORT="${NEKO_HTTP_PORT:-9200}" export NEKO_HTTP_PORT_1="${NEKO_HTTP_PORT_1:-$NEKO_HTTP_PORT}" diff --git a/d2ypp2/services/neko/docker-compose.yml b/d2ypp2/services/neko/docker-compose.yml index e36f762..0440988 100644 --- a/d2ypp2/services/neko/docker-compose.yml +++ b/d2ypp2/services/neko/docker-compose.yml @@ -4,6 +4,8 @@ x-neko-common: &neko-common shm_size: "${NEKO_SHM_SIZE:-512mb}" cap_add: - SYS_ADMIN + security_opt: + - apparmor:unconfined extra_hosts: - "host.docker.internal:host-gateway" diff --git a/d2ypp2/src/control_plane.py b/d2ypp2/src/control_plane.py index b357d8b..615132a 100644 --- a/d2ypp2/src/control_plane.py +++ b/d2ypp2/src/control_plane.py @@ -668,6 +668,15 @@ def _neko_status_message(instance_id: int, state: dict[str, Any]) -> str: return f"Neko {instance_id} 已停止" +async def _neko_reconfigure_stack(instance_id: int) -> tuple[str, str]: + if not SERVICE_CTL.is_file(): + raise RuntimeError("Neko container needs reconfigure, but service controller script is missing") + code, output = await _run_command([BASH_BIN, str(SERVICE_CTL), "neko", "reconfigure"], timeout=180.0) + if code != 0: + raise RuntimeError(f"Neko {instance_id} reconfigure failed: {output or 'neko reconfigure failed'}") + return f"Neko {instance_id} reconfigured with current WebRTC settings", output + + async def neko_instance_action(instance_id: int, action: str) -> dict[str, Any]: action = action.strip().lower() if action not in {"status", "start", "stop", "restart", "delete"}: @@ -687,11 +696,7 @@ async def neko_instance_action(instance_id: int, action: str) -> dict[str, Any]: if before.get("running"): message = f"Neko {instance_id} 已经在运行" elif before.get("exists"): - code, output = await _run_command(["docker", "start", container], timeout=45.0) - if code != 0: - raise RuntimeError(f"Neko {instance_id} 启动失败:{output or 'docker start failed'}") - message = f"Neko {instance_id} 已启动" - detail = output + message, detail = await _neko_reconfigure_stack(instance_id) else: if not SERVICE_CTL.is_file(): raise RuntimeError("Neko 容器不存在,且服务控制脚本缺失,无法重建") @@ -713,11 +718,7 @@ async def neko_instance_action(instance_id: int, action: str) -> dict[str, Any]: detail = output elif action == "restart": if before.get("exists"): - code, output = await _run_command(["docker", "restart", container], timeout=60.0) - if code != 0: - raise RuntimeError(f"Neko {instance_id} 重启失败:{output or 'docker restart failed'}") - message = f"Neko {instance_id} 已重启" - detail = output + message, detail = await _neko_reconfigure_stack(instance_id) else: if not SERVICE_CTL.is_file(): raise RuntimeError("Neko 容器不存在,且服务控制脚本缺失,无法重建") diff --git a/d2ypp2/tests/test_control_plane_services.py b/d2ypp2/tests/test_control_plane_services.py index 81958f2..b0be34c 100644 --- a/d2ypp2/tests/test_control_plane_services.py +++ b/d2ypp2/tests/test_control_plane_services.py @@ -150,6 +150,46 @@ class ControlPlaneServiceTests(unittest.TestCase): self.assertTrue(result["running"]) self.assertIn("重建", result["message"]) + def test_neko_instance_start_reconfigures_existing_stopped_container(self) -> None: + runner = AsyncMock( + side_effect=[ + (0, "exited"), + (0, "message=Neko WebRTC config reapplied"), + (0, "running"), + ] + ) + with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}): + with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"): + with patch("src.control_plane._run_command", runner): + result = asyncio.run(neko_instance_action(1, "start")) + + self.assertEqual(result["container"], "live-neko-1") + self.assertTrue(result["running"]) + self.assertIn("reconfigured", result["message"]) + reconfigure_cmd = runner.await_args_list[1].args[0] + self.assertEqual(reconfigure_cmd[-2:], ["neko", "reconfigure"]) + self.assertNotEqual(reconfigure_cmd[:2], ["docker", "start"]) + + def test_neko_instance_restart_reconfigures_existing_container(self) -> None: + runner = AsyncMock( + side_effect=[ + (0, "running"), + (0, "message=Neko WebRTC config reapplied"), + (0, "running"), + ] + ) + with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}): + with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"): + with patch("src.control_plane._run_command", runner): + result = asyncio.run(neko_instance_action(1, "restart")) + + self.assertEqual(result["container"], "live-neko-1") + self.assertTrue(result["running"]) + self.assertIn("reconfigured", result["message"]) + reconfigure_cmd = runner.await_args_list[1].args[0] + self.assertEqual(reconfigure_cmd[-2:], ["neko", "reconfigure"]) + self.assertNotEqual(reconfigure_cmd[:2], ["docker", "restart"]) + def test_network_stats_expose_realtime_and_total_bandwidth_fields(self) -> None: stats = network_iface_stats() for key in ("interfaces", "total_rx_bytes", "total_tx_bytes", "total_rx_bps", "total_tx_bps"): diff --git a/d2ypp2/tests/test_neko_config.py b/d2ypp2/tests/test_neko_config.py index 73b3a54..10cbe2c 100644 --- a/d2ypp2/tests/test_neko_config.py +++ b/d2ypp2/tests/test_neko_config.py @@ -113,6 +113,7 @@ class NekoConfigTests(unittest.TestCase): self.assertIn("./tampermonkey-seed:/etc/neko/tampermonkey-seed:ro", compose) self.assertNotIn("./no-managed-policies:/etc/chromium/policies/managed", compose) self.assertNotIn("./no-managed-policies:/etc/opt/chrome/policies/managed", compose) + self.assertIn("apparmor:unconfined", compose) self.assertIn("container_name: live-neko-1", compose) self.assertIn("container_name: live-neko-2", compose) self.assertIn("container_name: live-neko-3", compose) @@ -173,6 +174,7 @@ class NekoConfigTests(unittest.TestCase): self.assertIn('ENV_DISPLAY: ":88.0"', rendered) self.assertIn('DISPLAY: ":88.0"', rendered) self.assertEqual(rendered.count('"host.docker.internal:host-gateway"'), 4) + self.assertEqual(rendered.count("apparmor:unconfined"), 4) self.assertIn('NEKO_MANAGED_POLICIES: "1"', rendered) self.assertIn('NEKO_TAMPERMONKEY_REPAIR: "1"', rendered) self.assertIn('"./policies:/etc/chromium/policies/managed:ro"', rendered) @@ -223,6 +225,8 @@ class NekoConfigTests(unittest.TestCase): self.assertIn('path.startswith("/")', script) self.assertIn('value.get("location") == 8', script) self.assertIn("neko_managed_policies_enabled()", script) + self.assertIn("service_neko_restart()", service_ctl) + self.assertIn("service_neko_reconfigure", service_ctl) def test_tampermonkey_external_extension_seed_is_available_without_managed_policy(self) -> None: external = json.loads( diff --git a/d2ypp2/tests/test_web_dynamic_processes.py b/d2ypp2/tests/test_web_dynamic_processes.py index 75643d0..283add2 100644 --- a/d2ypp2/tests/test_web_dynamic_processes.py +++ b/d2ypp2/tests/test_web_dynamic_processes.py @@ -281,6 +281,30 @@ class WebDynamicProcessesTests(unittest.TestCase): self.assertNotIn("legacy-key", content) self.assertFalse(managed_exists) + def test_config_reads_allow_initial_duplicate_page_load_requests(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + config_dir = Path(tmp) + (config_dir / "youtube.ini").write_text("[youtube]\nkey = test-key\n", encoding="utf-8") + (config_dir / "URL_config.ini").write_text("https://live.example/room\n", encoding="utf-8") + + try: + web._READ_CONFIG_RECENT_REQUESTS.clear() + with patch("web.CONFIG_DIR", config_dir): + with patch("web.managed_youtube_ini_relpath", return_value="youtube.ini"): + first_ini = asyncio.run(web.get_config(_ReadRequest(), process="youtube")) + second_ini = asyncio.run(web.get_config(_ReadRequest(), process="youtube")) + with patch("web.allows_url_config", return_value=True): + with patch("web.managed_url_config_relpath", return_value="URL_config.ini"): + first_url = asyncio.run(web.get_url_config(_ReadRequest(), process="youtube")) + second_url = asyncio.run(web.get_url_config(_ReadRequest(), process="youtube")) + finally: + web._READ_CONFIG_RECENT_REQUESTS.clear() + + for response in (first_ini, second_ini, first_url, second_url): + self.assertEqual(response.status_code, 200) + self.assertIn("key = test-key", _json_body(second_ini)["content"]) + self.assertIn("live.example", _json_body(second_url)["content"]) + def test_save_url_config_updates_matching_youtube_pro_channel_store(self) -> None: captured: list[list[dict[str, object]]] = [] channels = [{"id": "lane1", "name": "Lane 1", "pm2Name": "youtube2__lane1", "urlLines": "old\n"}] diff --git a/d2ypp2/tools/render_neko_compose.py b/d2ypp2/tools/render_neko_compose.py index d1afe71..b002df7 100644 --- a/d2ypp2/tools/render_neko_compose.py +++ b/d2ypp2/tools/render_neko_compose.py @@ -108,6 +108,8 @@ def render(count: int) -> str: f" shm_size: {q(shm)}", " cap_add:", " - SYS_ADMIN", + " security_opt:", + " - apparmor:unconfined", " extra_hosts:", ' - "host.docker.internal:host-gateway"', f" container_name: live-neko-{idx}", diff --git a/d2ypp2/web-console/components/live-product/LiveControlApp.tsx b/d2ypp2/web-console/components/live-product/LiveControlApp.tsx index bc20574..8981630 100644 --- a/d2ypp2/web-console/components/live-product/LiveControlApp.tsx +++ b/d2ypp2/web-console/components/live-product/LiveControlApp.tsx @@ -568,6 +568,7 @@ export default function LiveControlApp() { const [serialResponse, setSerialResponse] = useState(""); const [studioOps, setStudioOps] = useState(null); const dashboardInFlightRef = useRef | null>(null); + const stackSummaryInFlightRef = useRef | null>(null); const processMonitorInFlightRef = useRef | null>(null); const currentProcRef = useRef(currentProc); const urlConfigRequestSeqRef = useRef(0); @@ -593,6 +594,24 @@ export default function LiveControlApp() { [base], ); + const refreshStackSummary = useCallback(async () => { + if (stackSummaryInFlightRef.current) return stackSummaryInFlightRef.current; + const task = (async () => { + try { + const stack = await fetchJson>("/stack/summary"); + setDash((prev) => ({ ...(prev ?? {}), stack })); + setDashErr(null); + setLastSyncedAt(Date.now()); + } catch (e) { + setDashErr((e as Error).message); + } finally { + stackSummaryInFlightRef.current = null; + } + })(); + stackSummaryInFlightRef.current = task; + return task; + }, [fetchJson]); + const refreshDashboard = useCallback(async () => { if (dashboardInFlightRef.current) return dashboardInFlightRef.current; const task = (async () => { @@ -737,10 +756,11 @@ export default function LiveControlApp() { if (!viewReady) return; if (view === "live_youtube" || view === "live_tiktok") { setLoading(false); + void refreshStackSummary(); return; } void refreshDashboard(); - }, [refreshDashboard, view, viewReady]); + }, [refreshDashboard, refreshStackSummary, view, viewReady]); useEffect(() => { if (!viewReady) return; @@ -767,25 +787,6 @@ export default function LiveControlApp() { currentProcRef.current = currentProc; }, [currentProc]); - useEffect(() => { - if (!currentProc || view !== "live_youtube") return; - void (async () => { - const targetProc = currentProcRef.current.trim(); - const requestId = ++urlConfigRequestSeqRef.current; - try { - const params = new URLSearchParams({ - process: targetProc, - _ts: String(Date.now()), - }); - const data = await fetchJson<{ content?: string }>(`/get_url_config?${params}`); - if (requestId !== urlConfigRequestSeqRef.current || targetProc !== currentProcRef.current.trim()) return; - setUrlConfig(data.content || ""); - } catch { - /* 保留当前草稿,避免临时读取失败把编辑器清空 */ - } - })(); - }, [currentProc, fetchJson, view]); - useEffect(() => { if (view !== "settings") return; void (async () => { diff --git a/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx b/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx index 2b209c3..7ad8659 100644 --- a/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx +++ b/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx @@ -674,6 +674,8 @@ export function LiveYoutubeUnmannedView({ const currentProcRef = useRef(currentProc); const urlRequestSeqRef = useRef(0); const ytIniRequestSeqRef = useRef(0); + const urlConfigReadInFlightRef = useRef>>({}); + const ytIniReadInFlightRef = useRef>>({}); const applySingleUrlDraft = useCallback( (next: string) => { @@ -689,6 +691,50 @@ export function LiveYoutubeUnmannedView({ setProUrlDraft(next); }, []); + const readUrlConfigContent = useCallback( + (targetPm2: string) => { + const target = targetPm2.trim(); + if (!target) return Promise.resolve(""); + const existing = urlConfigReadInFlightRef.current[target]; + if (existing) return existing; + const params = new URLSearchParams({ process: target, _ts: String(Date.now()) }); + const promise = fetchJson<{ content?: string }>(`/get_url_config?${params}`).then((data) => data.content ?? ""); + urlConfigReadInFlightRef.current[target] = promise; + promise.then( + () => { + if (urlConfigReadInFlightRef.current[target] === promise) delete urlConfigReadInFlightRef.current[target]; + }, + () => { + if (urlConfigReadInFlightRef.current[target] === promise) delete urlConfigReadInFlightRef.current[target]; + }, + ); + return promise; + }, + [fetchJson], + ); + + const readYoutubeIniContent = useCallback( + (targetPm2: string) => { + const target = targetPm2.trim(); + if (!target) return Promise.resolve(""); + const existing = ytIniReadInFlightRef.current[target]; + if (existing) return existing; + const params = new URLSearchParams({ process: target, _ts: String(Date.now()) }); + const promise = fetchJson<{ content?: string }>(`/get_config?${params}`).then((data) => data.content ?? ""); + ytIniReadInFlightRef.current[target] = promise; + promise.then( + () => { + if (ytIniReadInFlightRef.current[target] === promise) delete ytIniReadInFlightRef.current[target]; + }, + () => { + if (ytIniReadInFlightRef.current[target] === promise) delete ytIniReadInFlightRef.current[target]; + }, + ); + return promise; + }, + [fetchJson], + ); + useEffect(() => { const onVis = () => setPageVisible(document.visibilityState === "visible"); onVis(); @@ -734,13 +780,8 @@ export function LiveYoutubeUnmannedView({ } const requestId = ++urlRequestSeqRef.current; try { - const params = new URLSearchParams({ - process: targetProc, - _ts: String(Date.now()), - }); - const data = await fetchJson<{ content?: string }>(`/get_url_config?${params}`); + const c = await readUrlConfigContent(targetProc); if (requestId !== urlRequestSeqRef.current || targetProc !== currentProcRef.current.trim()) return; - const c = data.content ?? ""; if (urlListDirtyRef.current) return; if (mode === "single") applySingleUrlDraft(c); else { @@ -754,7 +795,7 @@ export function LiveYoutubeUnmannedView({ } catch { /* ignore */ } - }, [activeCh, applyProUrlDraft, applySingleUrlDraft, fetchJson, mode]); + }, [activeCh, applyProUrlDraft, applySingleUrlDraft, mode, readUrlConfigContent]); useEffect(() => { if (!currentProc || !urlAutoRefresh) return; @@ -777,13 +818,8 @@ export function LiveYoutubeUnmannedView({ urlListDirtyRef.current = false; const requestId = ++urlRequestSeqRef.current; try { - const params = new URLSearchParams({ - process: targetProc, - _ts: String(Date.now()), - }); - const data = await fetchJson<{ content?: string }>(`/get_url_config?${params}`); + const c = await readUrlConfigContent(targetProc); if (requestId !== urlRequestSeqRef.current || targetProc !== currentProcRef.current.trim()) return; - const c = data.content ?? ""; if (urlListDirtyRef.current) { setUrlFetchNote(t("检测到本地未保存修改,已保留当前草稿", "Kept the local unsaved draft")); return; @@ -889,7 +925,7 @@ export function LiveYoutubeUnmannedView({ const runtimeLogRow = rowForPm2(runtimeLogProc); useEffect(() => { if (mode !== "single" || !preferredSingleProc) return; - if (!currentProc) { + if (!currentProc || isYoutubeProPm2(currentProc)) { currentProcRef.current = preferredSingleProc; setCurrentProc(preferredSingleProc); } @@ -1072,16 +1108,12 @@ export function LiveYoutubeUnmannedView({ setYtIniStatus(null); try { const [urlResult, iniResult] = await Promise.allSettled([ - fetchJson<{ content?: string }>( - `/get_url_config?${new URLSearchParams({ process: target, _ts: String(Date.now()) })}`, - ), - fetchJson<{ content?: string }>( - `/get_config?${new URLSearchParams({ process: target, _ts: String(Date.now()) })}`, - ), + readUrlConfigContent(target), + readYoutubeIniContent(target), ]); if (urlRequestId === urlRequestSeqRef.current && target === currentProcRef.current.trim()) { if (urlResult.status === "fulfilled") { - applySingleUrlDraft(urlResult.value.content ?? ""); + applySingleUrlDraft(urlResult.value); setUrlFetchNote(t("单频道配置已实时同步", "Single-channel config synced")); } else { setUrlFetchNote(urlResult.reason instanceof Error ? urlResult.reason.message : String(urlResult.reason)); @@ -1089,7 +1121,7 @@ export function LiveYoutubeUnmannedView({ } if (iniRequestId === ytIniRequestSeqRef.current && target === currentProcRef.current.trim()) { if (iniResult.status === "fulfilled") { - const text = iniResult.value.content ?? ""; + const text = iniResult.value; setYoutubeIniText(text); setYtFields(parseYoutubeIniFields(text)); } else { @@ -1104,7 +1136,75 @@ export function LiveYoutubeUnmannedView({ } } }, - [applySingleUrlDraft, fetchJson, t], + [applySingleUrlDraft, readUrlConfigContent, readYoutubeIniContent, t], + ); + + const refreshProLaneFromServer = useCallback( + async (channel: YoutubeProChannel) => { + const target = resolveChannelPm2(channel).trim(); + if (!target) return; + const urlRequestId = ++urlRequestSeqRef.current; + const iniRequestId = ++ytIniRequestSeqRef.current; + urlListDirtyRef.current = false; + setUrlReloading(true); + setYtIniLoading(true); + setUrlFetchNote(t("正在同步当前线路配置...", "Syncing current lane config...")); + setYtIniStatus(null); + try { + const [urlResult, iniResult] = await Promise.allSettled([ + readUrlConfigContent(target), + readYoutubeIniContent(target), + ]); + if (urlRequestId === urlRequestSeqRef.current && target === currentProcRef.current.trim()) { + if (urlResult.status === "fulfilled") { + const remoteText = urlResult.value; + const localDraft = channel.urlLines ?? ""; + if (shouldPreserveLocalUrlDraft(localDraft, remoteText)) { + applyProUrlDraft(localDraft); + patchChannelLocalForPm2(target, { urlLines: localDraft }); + setUrlFetchNote(t("服务器暂无已保存 URL,已保留当前线路草稿", "Server has no saved URLs, kept this lane draft")); + } else { + applyProUrlDraft(remoteText); + patchChannelLocalForPm2(target, { urlLines: remoteText }); + setUrlFetchNote(t("当前线路地址已实时同步", "Current lane URLs synced")); + } + } else { + setUrlFetchNote(urlResult.reason instanceof Error ? urlResult.reason.message : String(urlResult.reason)); + } + } + if (iniRequestId === ytIniRequestSeqRef.current && target === currentProcRef.current.trim()) { + if (iniResult.status === "fulfilled") { + const text = iniResult.value; + const fields = parseYoutubeIniFields(text); + setYoutubeIniText(text); + setYtFields(fields); + if (fields.key.trim()) { + setLaneDrafts((prev) => { + const draft = prev[channel.id] ?? laneDraftFromChannel(channel); + if (draft.streamKey.trim() && draft.streamKey.trim() !== (channel.streamKey ?? "").trim()) return prev; + if (draft.streamKey.trim() === fields.key.trim()) return prev; + return { + ...prev, + [channel.id]: { + ...draft, + streamKey: fields.key.trim(), + }, + }; + }); + } + } else { + setYtIniStatus(iniResult.reason instanceof Error ? iniResult.reason.message : String(iniResult.reason)); + } + } + } finally { + if (urlRequestId === urlRequestSeqRef.current) setUrlReloading(false); + if (iniRequestId === ytIniRequestSeqRef.current) setYtIniLoading(false); + if (target === currentProcRef.current.trim()) { + setActiveViewRefreshToken((prev) => prev + 1); + } + } + }, + [applyProUrlDraft, patchChannelLocalForPm2, readUrlConfigContent, readYoutubeIniContent, t], ); const refreshProChannelsFromServer = useCallback(async () => { @@ -1123,10 +1223,11 @@ export function LiveYoutubeUnmannedView({ const pm2 = resolveChannelPm2(ch); currentProcRef.current = pm2; setCurrentProc(pm2); + void refreshProLaneFromServer(ch); } catch { /* keep current local channels when the server is temporarily unreachable */ } - }, [activeCh, applyProUrlDraft, fetchJson, setCurrentProc]); + }, [activeCh, applyProUrlDraft, fetchJson, refreshProLaneFromServer, setCurrentProc]); void refreshSingleProcessFromServer; @@ -1139,10 +1240,12 @@ export function LiveYoutubeUnmannedView({ return; } if (m === "single") { - const target = currentProcRef.current.trim() || preferredSingleProc || singleProcessOptions[0]?.pm2 || ""; + const current = currentProcRef.current.trim(); + const target = current && !isYoutubeProPm2(current) ? current : preferredSingleProc || singleProcessOptions[0]?.pm2 || ""; if (target) { currentProcRef.current = target; setCurrentProc(target); + void refreshSingleProcessFromServer(target); } } if (m === "pro" && channels.length) { @@ -1154,6 +1257,7 @@ export function LiveYoutubeUnmannedView({ const pm2 = resolveChannelPm2(ch); currentProcRef.current = pm2; setCurrentProc(pm2); + void refreshProLaneFromServer(ch); } } setMode(m); @@ -1170,6 +1274,8 @@ export function LiveYoutubeUnmannedView({ mode, notify, preferredSingleProc, + refreshProLaneFromServer, + refreshSingleProcessFromServer, setCurrentProc, singleProcessOptions, t, @@ -1185,8 +1291,9 @@ export function LiveYoutubeUnmannedView({ const pm2 = resolveChannelPm2(c); currentProcRef.current = pm2; setCurrentProc(pm2); + void refreshProLaneFromServer(c); }, - [applyProUrlDraft, setCurrentProc], + [applyProUrlDraft, refreshProLaneFromServer, setCurrentProc], ); useEffect(() => { @@ -1205,13 +1312,8 @@ export function LiveYoutubeUnmannedView({ setYtIniLoading(true); setYtIniStatus(null); try { - const params = new URLSearchParams({ - process: targetProc, - _ts: String(Date.now()), - }); - const data = await fetchJson<{ content?: string }>(`/get_config?${params}`); + const text = await readYoutubeIniContent(targetProc); if (requestId !== ytIniRequestSeqRef.current || targetProc !== currentProcRef.current.trim()) return; - const text = data.content ?? ""; setYoutubeIniText(text); setYtFields(parseYoutubeIniFields(text)); } catch (e) { @@ -1222,17 +1324,19 @@ export function LiveYoutubeUnmannedView({ setYtIniLoading(false); } } - }, [fetchJson]); + }, [readYoutubeIniContent]); useEffect(() => { if (!currentProc) return; if (mode === "pro") { if (!active || currentProc !== resolveChannelPm2(active)) return; + void pullUrlConfigFromServer(); + void loadYoutubeIni(); + setActiveViewRefreshToken((prev) => prev + 1); + return; } - void pullUrlConfigFromServer(); - void loadYoutubeIni(); - setActiveViewRefreshToken((prev) => prev + 1); - }, [active, activeCh, currentProc, loadYoutubeIni, mode, pullUrlConfigFromServer]); + void refreshSingleProcessFromServer(currentProc); + }, [active, activeCh, currentProc, loadYoutubeIni, mode, pullUrlConfigFromServer, refreshSingleProcessFromServer]); const persistActiveLaneDraft = useCallback( async () => { @@ -2497,6 +2601,7 @@ export function LiveYoutubeUnmannedView({ const next = e.target.value; currentProcRef.current = next; setCurrentProc(next); + void refreshSingleProcessFromServer(next); }} > {currentProc && !singleProcessOptions.some((entry) => entry.pm2 === currentProc) ? ( @@ -2906,6 +3011,12 @@ export function LiveYoutubeUnmannedView({ currentProcRef.current = resolveChannelPm2(nc); setCurrentProc(currentProcRef.current); applyProUrlDraft(""); + urlRequestSeqRef.current += 1; + ytIniRequestSeqRef.current += 1; + urlListDirtyRef.current = false; + setYoutubeIniText(""); + setYtFields(parseYoutubeIniFields("")); + setUrlFetchNote(t("新线路已切换,地址列表为空", "New lane selected with an empty URL list")); }} > @@ -2979,13 +3090,25 @@ export function LiveYoutubeUnmannedView({ className="inline-flex items-center gap-1 text-xs text-rose-300 hover:text-rose-200 disabled:opacity-30" onClick={() => { const next = channels.filter((c) => c.id !== active.id); + const nextActive = next[0] ?? null; setLaneDrafts((prev) => { const clone = { ...prev }; delete clone[active.id]; return clone; }); persistChannels(next, { force: true }); - setActiveCh(next[0]?.id || ""); + setActiveCh(nextActive?.id || ""); + if (nextActive) { + const pm2 = resolveChannelPm2(nextActive); + currentProcRef.current = pm2; + setCurrentProc(pm2); + applyProUrlDraft((nextActive.urlLines ?? "").trim()); + void refreshProLaneFromServer(nextActive); + } else { + currentProcRef.current = ""; + setCurrentProc(""); + applyProUrlDraft(""); + } }} > diff --git a/d2ypp2/web.py b/d2ypp2/web.py index 5e035b3..e9d2864 100644 --- a/d2ypp2/web.py +++ b/d2ypp2/web.py @@ -809,8 +809,9 @@ _NO_STORE_HEADERS = { "Expires": "0", } -_READ_CONFIG_MIN_INTERVAL_SECONDS = 0.45 -_READ_CONFIG_LAST_SEEN: dict[tuple[str, str, str], float] = {} +_READ_CONFIG_WINDOW_SECONDS = 2.0 +_READ_CONFIG_MAX_REQUESTS_PER_WINDOW = 24 +_READ_CONFIG_RECENT_REQUESTS: dict[tuple[str, str, str], list[float]] = {} def _client_host(request: Request) -> str: @@ -822,15 +823,20 @@ def _client_host(request: Request) -> str: def _reject_config_read_storm(request: Request, endpoint: str, process: str) -> JSONResponse | None: now = time.monotonic() - if len(_READ_CONFIG_LAST_SEEN) > 2048: - cutoff = now - 30.0 - for key, seen_at in list(_READ_CONFIG_LAST_SEEN.items()): - if seen_at < cutoff: - _READ_CONFIG_LAST_SEEN.pop(key, None) + if len(_READ_CONFIG_RECENT_REQUESTS) > 2048: + cutoff = now - _READ_CONFIG_WINDOW_SECONDS + for existing_key, seen_at in list(_READ_CONFIG_RECENT_REQUESTS.items()): + recent_for_key = [item for item in seen_at if item >= cutoff] + if recent_for_key: + _READ_CONFIG_RECENT_REQUESTS[existing_key] = recent_for_key + else: + _READ_CONFIG_RECENT_REQUESTS.pop(existing_key, None) key = (_client_host(request), endpoint, (process or "").strip()) - last = _READ_CONFIG_LAST_SEEN.get(key, 0.0) - _READ_CONFIG_LAST_SEEN[key] = now - if now - last >= _READ_CONFIG_MIN_INTERVAL_SECONDS: + cutoff = now - _READ_CONFIG_WINDOW_SECONDS + recent = [item for item in _READ_CONFIG_RECENT_REQUESTS.get(key, []) if item >= cutoff] + recent.append(now) + _READ_CONFIG_RECENT_REQUESTS[key] = recent + if len(recent) <= _READ_CONFIG_MAX_REQUESTS_PER_WINDOW: return None return JSONResponse( {"error": "刷新过快,请稍后重试"}, diff --git a/origin) b/origin) new file mode 100644 index 0000000..e69de29