douyinWEB/backend/app/host_profile.py
eric 732d93e5d4 Add VPS/physical host profile switch and document nomadro topology.
Header toggle stops app egress+Neko and enables exclusive live on VPS mode; README covers dylive/dy.com/dy.cn roles.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 01:20:53 -05:00

193 lines
6.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""Host profile: VPS (lean) vs physical (full Neko + ShellCrash).
Does **not** stop VPS edge systemd units (sing-box / frpp / wg-quick@wg-dy*).
Those are infrastructure for the physical site, not app「网络」toggles.
"""
from __future__ import annotations
import os
from typing import Any
PROFILES = ("vps", "physical")
_KEY = "host_profile"
def _settings() -> dict[str, Any]:
from . import db
return dict(db.get_settings_map())
def infer_profile(cfg: dict[str, Any] | None = None) -> str:
s = dict(cfg) if cfg is not None else _settings()
raw = str(s.get(_KEY) or "").strip().lower()
if raw in PROFILES:
return raw
edge = str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip()
if edge and edge not in {"127.0.0.1", "localhost", "::1"}:
return "physical"
bind = str(os.environ.get("DY_NEKO_HTTP_BIND") or "").strip()
if bind in {"0.0.0.0", "*"}:
return "physical"
return "vps"
def status() -> dict[str, Any]:
s = _settings()
profile = infer_profile(s)
return {
"ok": True,
"profile": profile,
"stored": str(s.get(_KEY) or "").strip().lower() in PROFILES,
"profiles": list(PROFILES),
"effects": {
"vps": [
"egress / ShellCrash / 业务 SOCKS 全部关闭",
"全部 Neko 停止并关闭 neko_enabled",
"单路独占默认开启",
],
"physical": [
"业务出口切回 ShellCrash(不自动强起边缘 WG/FRP)",
"单路独占默认关闭(允许多 Neko 预热)",
"不自动拉起全部 Neko(由分配页按需开启)",
],
},
"never_touches": [
"sing-box.service",
"frpp.service",
"wg-quick@wg-dy.service",
"wg-quick@wg-dy-cn.service",
],
}
def _disable_all_neko() -> dict[str, Any]:
from . import yt_assign_db
from . import youtube_neko
from .db import _connect, _lock
disabled = 0
with _lock:
conn = _connect()
try:
yt_assign_db.ensure_yt_assign_tables(conn)
cur = conn.execute(
"UPDATE yt_assign_groups SET neko_enabled = 0 WHERE neko_enabled != 0"
)
disabled = int(cur.rowcount or 0)
conn.commit()
finally:
conn.close()
stopped = youtube_neko.stop_instances_except(0)
try:
youtube_neko.sync_for_groups(
yt_assign_db.list_groups(include_urls=False),
reconcile_running=True,
)
except Exception as exc:
return {
"ok": False,
"disabled_flags": disabled,
"stopped_containers": stopped,
"error": str(exc)[:300],
}
return {"ok": True, "disabled_flags": disabled, "stopped_containers": stopped}
def apply_profile(profile: str) -> dict[str, Any]:
from . import db
from . import egress_hub
from . import shellcrash_hub
from . import singbox_manager
raw = str(profile or "").strip().lower()
if raw not in PROFILES:
raise ValueError("profile must be vps or physical")
steps: dict[str, Any] = {}
if raw == "vps":
try:
steps["egress"] = egress_hub.apply_mode(
"off",
chain=False,
cover_neko_flag=False,
cover_relay_flag=False,
cover_uploads_flag=False,
refresh_neko=False,
)
except Exception as exc:
steps["egress"] = {"ok": False, "error": str(exc)[:300]}
try:
steps["singbox_app"] = singbox_manager.stop()
except Exception as exc:
steps["singbox_app"] = {"ok": False, "error": str(exc)[:300]}
try:
steps["shellcrash"] = shellcrash_hub.action("stop")
except Exception as exc:
steps["shellcrash"] = {"ok": False, "skipped": True, "error": str(exc)[:300]}
steps["neko"] = _disable_all_neko()
# Exclusive-live in-memory state is applied in apply_profile_async.
db.update_settings_map(
{
_KEY: "vps",
"youtube_relay_exclusive_live": True,
"global_socks_enabled": False,
"shorts_upload_socks_enabled": False,
"egress_chain_residential": False,
}
)
steps["settings"] = {"host_profile": "vps", "youtube_relay_exclusive_live": True}
else:
try:
steps["egress"] = egress_hub.apply_mode(
"shellcrash",
chain=False,
refresh_neko=False,
)
except Exception as exc:
# ShellCrash may be absent on pure VPS — still store profile + exclusive off.
db.update_settings_map({"egress_mode": "shellcrash"})
steps["egress"] = {"ok": False, "error": str(exc)[:300], "settings_only": True}
db.update_settings_map(
{
_KEY: "physical",
"youtube_relay_exclusive_live": False,
}
)
steps["settings"] = {
"host_profile": "physical",
"youtube_relay_exclusive_live": False,
"neko": "not_auto_started",
}
steps["neko"] = {"ok": True, "note": "physical: leave Neko as-is; enable per group in assign UI"}
return {"ok": True, "profile": raw, "steps": steps, **status()}
async def apply_profile_async(profile: str) -> dict[str, Any]:
"""Async wrapper so exclusive-live pipeline state stays consistent."""
import asyncio
from . import db
from . import youtube_relay_pipeline
raw = str(profile or "").strip().lower()
result = await asyncio.to_thread(apply_profile, raw)
# Re-apply exclusive via pipeline so in-memory winner/pause state matches.
exclusive_on = raw == "vps"
try:
result["steps"]["exclusive_live"] = await youtube_relay_pipeline.set_exclusive_live(exclusive_on)
except Exception as exc:
db.update_settings_map({"youtube_relay_exclusive_live": exclusive_on})
result["steps"]["exclusive_live"] = {"ok": False, "error": str(exc)[:300], "settings_written": True}
result["profile"] = raw
return result