douyinWEB/backend/app/egress_hub.py
hackrobot 1e8eb0130a Sync dylive production working tree to test3.
Include latest server fixes for yt-long/disk/ops and related frontend.
Exclude .bak scratch files.
2026-10-14 07:04:18 +00:00

615 lines
20 KiB
Python
Raw Permalink 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 -*-
"""Business egress for DouyinWEB.
US VPS (primary):
off → datacenter IP direct
residential → 127.0.0.1:17891 (douyinweb-singbox) → static residential SOCKS
NEVER touches host sing-box.service / v2ray-agent
Physical China (legacy, optional):
shellcrash → 127.0.0.1:7890 (+ optional dialer-proxy residential chain)
Douyin scrape/CDN stays DIRECT in all modes (callers must not inject proxy).
"""
from __future__ import annotations
import shutil
import subprocess
import time
from pathlib import Path
from typing import Any
from .config import BACKEND, ROOT
from .global_socks import CONFIG_DIR, LOCAL_MIXED_HOST, LOCAL_MIXED_PORT, local_mixed_url
MODES = ("off", "shellcrash", "residential")
PROXYCHAINS_CONF = CONFIG_DIR / "proxychains.conf"
RESIDENTIAL_PROXY_NAME = "dy-residential"
DEFAULT_DIALER = "dialer"
_MODE_KEY = "egress_mode"
_CHAIN_KEY = "egress_chain_residential"
_NEKO_KEY = "egress_cover_neko"
_RELAY_KEY = "egress_cover_relay"
_UPLOADS_KEY = "egress_cover_uploads"
def _settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
if cfg is not None:
return dict(cfg)
from . import db
return dict(db.get_settings_map())
def _is_vps_host(cfg: dict[str, Any] | None = None) -> bool:
try:
from . import host_profile
return host_profile.infer_profile(cfg) == "vps"
except Exception:
return True
def get_mode(cfg: dict[str, Any] | None = None) -> str:
s = _settings(cfg)
raw = str(s.get(_MODE_KEY) or "").strip().lower()
if raw in MODES:
return raw
# Legacy toggles → residential on VPS, shellcrash elsewhere
if s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled"):
return "residential" if _is_vps_host(s) else "shellcrash"
if _is_vps_host(s):
return "off"
return "shellcrash"
def local_residential_http_proxy() -> str:
return local_mixed_url()
def local_residential_socks() -> str:
return f"socks5://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}"
def google_http_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Proxy for Google / YouTube / TikTok / overseas APIs. Douyin stays DIRECT."""
mode = get_mode(cfg)
if mode == "residential":
return local_residential_http_proxy()
if mode == "shellcrash":
return _host_http_proxy(cfg)
# Soft path: ShellCrash still running on physical while mode off
if not _is_vps_host(cfg):
try:
from . import shellcrash_hub
st = shellcrash_hub.status() or {}
if st.get("running"):
return f"http://127.0.0.1:{shellcrash_mixed_port(cfg)}"
except Exception:
pass
return ""
def google_httpx_kwargs(*, timeout: float = 45.0, cfg: dict[str, Any] | None = None) -> dict[str, Any]:
kw: dict[str, Any] = {"timeout": timeout, "trust_env": False}
proxy = google_http_proxy(cfg)
if proxy:
kw["proxy"] = proxy
return kw
def google_http_proxy_candidates(
cfg: dict[str, Any] | None = None,
*,
prefer: str = "",
) -> list[str]:
"""Ordered Google egress attempts.
Residential / ShellCrash first when enabled; on US VPS always append direct
so flaky SOCKS cannot permanently mark Shorts OAuth as「异常」.
"""
out: list[str] = []
primary = str(prefer or "").strip() or google_http_proxy(cfg)
if primary:
out.append(primary)
# Direct fallback on VPS (datacenter reaches Google; residential may timeout).
if _is_vps_host(cfg) and "" not in out:
out.append("")
if not out:
out.append("")
# de-dupe preserving order
seen: set[str] = set()
uniq: list[str] = []
for p in out:
if p in seen:
continue
seen.add(p)
uniq.append(p)
return uniq
def httpx_kwargs_for_proxy(proxy: str, *, timeout: float = 45.0) -> dict[str, Any]:
kw: dict[str, Any] = {"timeout": timeout, "trust_env": False}
p = str(proxy or "").strip()
if p:
kw["proxy"] = p
return kw
overseas_httpx_kwargs = google_httpx_kwargs
overseas_http_proxy = google_http_proxy
def chain_residential(cfg: dict[str, Any] | None = None) -> bool:
"""ShellCrash dialer-proxy chain (physical only). VPS residential does not use this."""
s = _settings(cfg)
if get_mode(s) == "residential":
return False
if _CHAIN_KEY in s:
return bool(s.get(_CHAIN_KEY)) and get_mode(s) == "shellcrash"
return bool(s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled")) and get_mode(s) == "shellcrash"
def cover_neko(cfg: dict[str, Any] | None = None) -> bool:
s = _settings(cfg)
if _NEKO_KEY in s:
return bool(s.get(_NEKO_KEY))
return get_mode(s) != "off"
def cover_relay(cfg: dict[str, Any] | None = None) -> bool:
s = _settings(cfg)
if _RELAY_KEY in s:
return bool(s.get(_RELAY_KEY))
return get_mode(s) in {"shellcrash", "residential"}
def cover_uploads(cfg: dict[str, Any] | None = None) -> bool:
s = _settings(cfg)
if _UPLOADS_KEY in s:
return bool(s.get(_UPLOADS_KEY))
return get_mode(s) != "off"
def shellcrash_mixed_port(cfg: dict[str, Any] | None = None) -> int:
try:
from . import shellcrash_hub
st = shellcrash_hub.status()
port = int(st.get("mixed_port") or 7890)
return port if port > 0 else 7890
except Exception:
return 7890
def _host_http_proxy(cfg: dict[str, Any] | None = None) -> str:
if get_mode(cfg) != "shellcrash":
return ""
return f"http://127.0.0.1:{shellcrash_mixed_port(cfg)}"
def resolve_http_proxy(cfg: dict[str, Any] | None = None) -> str:
return google_http_proxy(cfg)
def resolve_upload_proxy(cfg: dict[str, Any] | None = None) -> str:
if get_mode(cfg) == "off" or not cover_uploads(cfg):
return ""
return google_http_proxy(cfg)
def resolve_business_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Unified overseas business proxy (uploads / OAuth / TikTok fallback)."""
return resolve_upload_proxy(cfg) or google_http_proxy(cfg)
def neko_browser_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Chromium inside Neko → host local mixed (no upstream credentials in URL)."""
import os
physical = bool(str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip())
mode = get_mode(cfg)
if mode == "off":
return ""
if not cover_neko(cfg) and not physical:
return ""
if mode == "residential":
return f"http://host.docker.internal:{LOCAL_MIXED_PORT}"
return f"http://host.docker.internal:{shellcrash_mixed_port(cfg)}"
def write_proxychains_conf(cfg: dict[str, Any] | None = None) -> Path:
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
mode = get_mode(cfg)
if mode == "off":
PROXYCHAINS_CONF.write_text(
"# egress off\nstrict_chain\nproxy_dns\n[ProxyList]\n",
encoding="utf-8",
)
return PROXYCHAINS_CONF
if mode == "residential":
port = LOCAL_MIXED_PORT
else:
port = shellcrash_mixed_port(cfg)
text = (
"strict_chain\n"
"proxy_dns\n"
"tcp_read_time_out 15000\n"
"tcp_connect_time_out 8000\n"
"localnet 127.0.0.0/8\n"
"localnet 10.0.0.0/8\n"
"localnet 192.168.0.0/16\n"
"[ProxyList]\n"
f"socks5 127.0.0.1 {port}\n"
)
PROXYCHAINS_CONF.write_text(text, encoding="utf-8")
try:
import os
os.chmod(PROXYCHAINS_CONF, 0o600)
except Exception:
pass
return PROXYCHAINS_CONF
def proxychains_bin() -> str:
return shutil.which("proxychains4") or shutil.which("proxychains") or ""
def wrap_ffmpeg_cmd(cmd: list[str], cfg: dict[str, Any] | None = None) -> list[str]:
if get_mode(cfg) == "off" or not cover_relay(cfg):
return list(cmd)
pc = proxychains_bin()
if not pc:
return list(cmd)
write_proxychains_conf(cfg)
return [pc, "-q", "-f", str(PROXYCHAINS_CONF), *cmd]
def ffmpeg_uses_proxy(cfg: dict[str, Any] | None = None) -> bool:
return get_mode(cfg) != "off" and cover_relay(cfg) and bool(proxychains_bin())
def apply_mode(
mode: str,
*,
chain: bool | None = None,
cover_neko_flag: bool | None = None,
cover_relay_flag: bool | None = None,
cover_uploads_flag: bool | None = None,
refresh_neko: bool = True,
dialer: str | None = None,
cfg: dict[str, Any] | None = None,
) -> dict[str, Any]:
from . import db
from . import singbox_manager
raw = str(mode or "off").strip().lower()
if raw not in MODES:
raise ValueError(f"unsupported egress mode: {raw}")
mode = raw
s = _settings(cfg)
# dialer-proxy chain only meaningful with ShellCrash
if chain is None:
chain = chain_residential(s) if mode == "shellcrash" else False
chain = bool(chain) and mode == "shellcrash"
if cover_neko_flag is None:
cover_neko_flag = mode != "off"
if cover_relay_flag is None:
cover_relay_flag = mode in {"shellcrash", "residential"}
if cover_uploads_flag is None:
cover_uploads_flag = mode != "off"
socks_on = mode == "residential" or (mode == "shellcrash" and chain)
updates: dict[str, Any] = {
_MODE_KEY: mode,
_CHAIN_KEY: chain,
_NEKO_KEY: bool(cover_neko_flag),
_RELAY_KEY: bool(cover_relay_flag),
_UPLOADS_KEY: bool(cover_uploads_flag),
"global_socks_enabled": socks_on,
"shorts_upload_socks_enabled": socks_on,
}
db.update_settings_map(updates)
s = db.get_settings_map()
chain_result: dict[str, Any] = {"skipped": True}
residential_result: dict[str, Any] = {"skipped": True}
if mode == "residential":
from . import global_socks
prof = global_socks.active_profile(s)
if not prof:
raise ValueError("已启用静态住宅 IP,但未配置 SOCKS5 账号(网络页「业务 SOCKS」填写)")
# Start DouyinWEB forwarder only — never host sing-box.service
residential_result = singbox_manager.apply_from_settings(s)
if not residential_result.get("ok") and not residential_result.get("running"):
raise ValueError(str(residential_result.get("error") or "douyinweb-singbox 启动失败"))
else:
# Leaving residential: stop app forwarder only
try:
residential_result = {**singbox_manager.stop(), "note": "stopped douyinweb-singbox"}
except Exception as exc:
residential_result = {"ok": False, "error": str(exc)}
if mode == "shellcrash":
from . import shellcrash_hub
if chain:
from . import global_socks
prof = global_socks.active_profile(s)
if not prof:
raise ValueError("已勾选住宅落地,但未配置 SOCKS5 账号(在下方业务 SOCKS 填写)")
chain_result = shellcrash_hub.apply_residential_chain(
prof,
dialer=(dialer or DEFAULT_DIALER).strip() or DEFAULT_DIALER,
)
else:
try:
chain_result = shellcrash_hub.apply_profile(
shellcrash_hub.DEFAULT_PROFILE,
shellcrash_hub.DEFAULT_NODE,
)
except Exception as exc:
chain_result = {"ok": False, "error": str(exc)}
pc_path = ""
if mode != "off" and (cover_relay_flag or cover_uploads_flag):
pc_path = str(write_proxychains_conf(s))
neko_result: dict[str, Any] = {"skipped": True}
if refresh_neko:
try:
from . import youtube_neko
neko_result = youtube_neko.refresh_compose_for_egress()
except Exception as exc:
neko_result = {"ok": False, "error": str(exc)}
return {
"ok": True,
"egress": status(s),
"chain": chain_result,
"residential": residential_result,
"proxychains_conf": pc_path,
"neko": neko_result,
"v2ray_agent": singbox_manager.host_v2ray_agent_status(),
}
def probe(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
mode = get_mode(cfg)
proxy = google_http_proxy(cfg) if mode != "off" else ""
targets = [
("google", "https://www.google.com/generate_204"),
("youtube", "https://www.youtube.com/"),
("ip", "https://api.ipify.org"),
("douyin", "https://www.douyin.com/"),
]
rows = []
for name, url in targets:
if name == "douyin":
rows.append(_curl_probe("douyin_direct", url, proxy=""))
if proxy:
rows.append(_curl_probe("douyin_via_proxy", url, proxy=proxy))
continue
if name == "ip":
rows.append(_curl_probe_body("exit_ip", url, proxy=proxy))
rows.append(_curl_probe_body("exit_ip_direct", url, proxy=""))
continue
rows.append(_curl_probe(name, url, proxy=proxy))
rows.append(_curl_probe(f"{name}_direct", url, proxy=""))
return {
"ok": True,
"mode": mode,
"chain_residential": chain_residential(cfg),
"proxy": proxy,
"probes": rows,
"policy": {"douyin": "DIRECT", "domains": ["*.douyin.com", "*.douyincdn.com", "…"]},
"at": int(time.time()),
}
def _curl_probe(name: str, url: str, *, proxy: str) -> dict[str, Any]:
cmd = ["curl", "-sS", "-m", "10", "-o", "/dev/null", "-w", "%{http_code}"]
if proxy:
cmd.extend(["-x", proxy])
cmd.append(url)
t0 = time.time()
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=14, check=False)
code = (p.stdout or "").strip() or "000"
ok = code in {"200", "204", "301", "302"}
return {
"target": name,
"ok": ok,
"http_code": code,
"elapsed_ms": int((time.time() - t0) * 1000),
"via": proxy or "direct",
"error": (p.stderr or "").strip()[:160] if not ok else "",
}
except Exception as exc:
return {
"target": name,
"ok": False,
"http_code": "000",
"elapsed_ms": int((time.time() - t0) * 1000),
"via": proxy or "direct",
"error": str(exc)[:160],
}
def _curl_probe_body(name: str, url: str, *, proxy: str) -> dict[str, Any]:
cmd = ["curl", "-sS", "-m", "10"]
if proxy:
cmd.extend(["-x", proxy])
cmd.append(url)
t0 = time.time()
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=14, check=False)
body = (p.stdout or "").strip()[:64]
ok = p.returncode == 0 and bool(body)
return {
"target": name,
"ok": ok,
"http_code": "200" if ok else "000",
"elapsed_ms": int((time.time() - t0) * 1000),
"via": proxy or "direct",
"body": body,
"error": (p.stderr or "").strip()[:160] if not ok else "",
}
except Exception as exc:
return {
"target": name,
"ok": False,
"http_code": "000",
"elapsed_ms": int((time.time() - t0) * 1000),
"via": proxy or "direct",
"body": "",
"error": str(exc)[:160],
}
def status(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
from . import singbox_manager
s = _settings(cfg)
mode = get_mode(s)
chain = chain_residential(s)
vps = _is_vps_host(s)
sc: dict[str, Any] = {}
try:
from . import shellcrash_hub
sc = shellcrash_hub.status() or {}
except Exception:
sc = {}
host_proxy = google_http_proxy(s)
neko_proxy = neko_browser_proxy(s)
pc = proxychains_bin()
sb = singbox_manager.status()
if mode == "residential":
exit_label = "static-residential"
elif chain:
exit_label = RESIDENTIAL_PROXY_NAME
else:
exit_label = sc.get("selected_node") or "direct"
modes_ui = [
{"id": "off", "label": "机房直连", "description": "美国 VPS 默认:业务用机房 IP"},
{
"id": "residential",
"label": "静态住宅 IP",
"description": f"本机 :{LOCAL_MIXED_PORT} → 住宅 SOCKS(不动 v2ray-agent)",
"ready": True,
},
]
if not vps:
modes_ui.append(
{
"id": "shellcrash",
"label": "ShellCrash",
"description": "物理机出海 :7890;可选住宅链式",
"ready": bool(sc.get("running") or sc.get("installed")),
}
)
return {
"mode": mode,
"chain_residential": chain,
"host_profile": "vps" if vps else "physical",
"modes": modes_ui,
"cover": {
"neko": cover_neko(s),
"relay": cover_relay(s),
"uploads": cover_uploads(s),
},
"host_proxy": host_proxy,
"neko_proxy": neko_proxy,
"exit_node": exit_label,
"dialer": DEFAULT_DIALER,
"residential_proxy_name": RESIDENTIAL_PROXY_NAME,
"socks_url": (
local_residential_socks()
if mode == "residential"
else (f"socks5://127.0.0.1:{shellcrash_mixed_port(s)}" if mode == "shellcrash" else "")
),
"local_mixed": local_residential_http_proxy() if mode == "residential" else "",
"proxychains": {
"installed": bool(pc),
"bin": pc,
"conf": str(PROXYCHAINS_CONF) if PROXYCHAINS_CONF.is_file() else "",
"relay_active": ffmpeg_uses_proxy(s),
},
"douyinweb_singbox": {
"running": bool(sb.get("running")),
"unit": sb.get("unit"),
"mixed": sb.get("mixed"),
"config": sb.get("config"),
},
"v2ray_agent": sb.get("v2ray_agent") or singbox_manager.host_v2ray_agent_status(),
"shellcrash": {
"running": bool(sc.get("running")),
"mixed_port": sc.get("mixed_port") or "7890",
"selected_node": sc.get("selected_node"),
},
"matrix": [
{
"id": "neko",
"label": "Neko Chrome / X",
"active": bool(neko_proxy),
"detail": neko_proxy or "直连(机房 IP)",
},
{
"id": "relay",
"label": "直播推流 FFmpeg",
"active": ffmpeg_uses_proxy(s),
"detail": (
f"proxychains → {exit_label}"
if ffmpeg_uses_proxy(s)
else ("缺 proxychains" if cover_relay(s) and not pc else "直连(机房 IP)")
),
},
{
"id": "uploads",
"label": "Shorts / 长视频 / TikTok",
"active": bool(resolve_upload_proxy(s)),
"detail": (host_proxy + f" → {exit_label}") if resolve_upload_proxy(s) else "直连(机房 IP)",
},
],
"hints": _hints(mode, chain, sc, pc, sb, vps),
"app_root": str(ROOT),
"backend": str(BACKEND),
}
def _hints(
mode: str,
chain: bool,
sc: dict[str, Any],
pc: str,
sb: dict[str, Any],
vps: bool,
) -> list[str]:
out: list[str] = []
out.append("硬规则:*.douyin.com / 抖音 CDN 始终直连,不进住宅代理")
out.append("绝不操作宿主机 sing-box.service(v2ray-agent);仅 douyinweb-singbox")
if mode == "residential":
if not sb.get("running"):
out.append("douyinweb-singbox 未运行 — 检查 SOCKS 账号后重新「应用」")
else:
out.append(f"业务入口 {local_residential_http_proxy()} → 静态住宅;默认关=机房 IP")
if mode == "off" and vps:
out.append("当前机房 IP 直出(美国 VPS 默认可访问 Google/YouTube)")
if mode == "shellcrash" and not sc.get("running"):
out.append("ShellCrash 未运行 — 先启动再应用")
if mode == "shellcrash" and chain:
out.append("住宅落地 = ShellCrash dialer-proxy 链式(物理机)")
if mode != "off" and not pc:
out.append("未安装 proxychains4 — 直播推流无法走代理")
return out