Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP. Co-authored-by: Cursor <cursoragent@cursor.com>
462 lines
15 KiB
Python
462 lines
15 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Business egress — always via ShellCrash on China physical hosts.
|
||
|
||
Correct model (虚空终端 dialer-proxy):
|
||
App → 127.0.0.1:7890 (ShellCrash mixed)
|
||
├─ 默认:选机场节点直接出海
|
||
└─ 勾选「住宅落地」:选 dy-residential(socks5 + dialer-proxy)
|
||
→ 先经 ShellCrash 前置节点拨号,再连住宅 SOCKS 落地
|
||
(家宽无法直连海外住宅 SOCKS)
|
||
|
||
Docs: https://wiki.metacubex.one/config/proxies/dialer-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
|
||
|
||
MODES = ("off", "shellcrash")
|
||
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 get_mode(cfg: dict[str, Any] | None = None) -> str:
|
||
s = _settings(cfg)
|
||
raw = str(s.get(_MODE_KEY) or "").strip().lower()
|
||
# Legacy: "residential" meant chain-on ShellCrash, never direct SOCKS.
|
||
if raw == "residential":
|
||
return "shellcrash"
|
||
if raw in MODES:
|
||
return raw
|
||
if s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled"):
|
||
return "shellcrash"
|
||
# Default ON for China physical: all non-Douyin business via ShellCrash.
|
||
# Explicit "off" in settings still wins (handled above via MODES).
|
||
return "shellcrash"
|
||
|
||
|
||
def google_http_proxy(cfg: dict[str, Any] | None = None) -> str:
|
||
"""Proxy for Google / YouTube / TikTok / overseas APIs. Douyin stays DIRECT via Clash rules.
|
||
|
||
- shellcrash mode → mixed :7890
|
||
- mode off but ShellCrash still running → still use it (physical soft path)
|
||
- mode off + no ShellCrash → empty string (pure VPS direct)
|
||
"""
|
||
if get_mode(cfg) == "shellcrash":
|
||
return _host_http_proxy(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
|
||
|
||
|
||
# Alias — overseas APIs (TikTok Open API, etc.) share the same egress.
|
||
overseas_httpx_kwargs = google_httpx_kwargs
|
||
overseas_http_proxy = google_http_proxy
|
||
|
||
|
||
def chain_residential(cfg: dict[str, Any] | None = None) -> bool:
|
||
s = _settings(cfg)
|
||
if _CHAIN_KEY in s:
|
||
return bool(s.get(_CHAIN_KEY))
|
||
# Legacy residential mode / socks toggle → chain on
|
||
raw = str(s.get(_MODE_KEY) or "").strip().lower()
|
||
if raw == "residential":
|
||
return True
|
||
return bool(s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled"))
|
||
|
||
|
||
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) == "shellcrash"
|
||
|
||
|
||
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:
|
||
if get_mode(cfg) == "off":
|
||
return ""
|
||
return _host_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 _host_http_proxy(cfg)
|
||
|
||
|
||
def neko_browser_proxy(cfg: dict[str, Any] | None = None) -> str:
|
||
"""Chromium inside Neko → host ShellCrash.
|
||
|
||
Physical (DY_NEKO_EDGE_UPSTREAM set): always inject proxy unless egress mode is explicit off.
|
||
"""
|
||
import os
|
||
|
||
physical = bool(str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip())
|
||
if get_mode(cfg) == "off":
|
||
return ""
|
||
if not cover_neko(cfg) and not physical:
|
||
return ""
|
||
return f"http://host.docker.internal:{shellcrash_mixed_port(cfg)}"
|
||
|
||
|
||
def write_proxychains_conf(cfg: dict[str, Any] | None = None) -> Path:
|
||
"""Always point proxychains at ShellCrash mixed SOCKS — never raw residential."""
|
||
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||
if get_mode(cfg) != "shellcrash":
|
||
PROXYCHAINS_CONF.write_text(
|
||
"# egress off\nstrict_chain\nproxy_dns\n[ProxyList]\n",
|
||
encoding="utf-8",
|
||
)
|
||
return PROXYCHAINS_CONF
|
||
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")
|
||
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 shellcrash_hub
|
||
from . import singbox_manager
|
||
|
||
raw = str(mode or "off").strip().lower()
|
||
if raw == "residential":
|
||
mode = "shellcrash"
|
||
if chain is None:
|
||
chain = True
|
||
elif raw not in MODES:
|
||
raise ValueError(f"unsupported egress mode: {raw}")
|
||
else:
|
||
mode = raw
|
||
|
||
s = _settings(cfg)
|
||
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 == "shellcrash"
|
||
if cover_uploads_flag is None:
|
||
cover_uploads_flag = mode != "off"
|
||
|
||
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),
|
||
# Keep legacy flags aligned with «住宅链式» checkbox only (not a separate engine).
|
||
"global_socks_enabled": chain,
|
||
"shorts_upload_socks_enabled": chain,
|
||
}
|
||
db.update_settings_map(updates)
|
||
s = db.get_settings_map()
|
||
|
||
# Never run douyinweb-singbox as China residential path — stop if leftover.
|
||
try:
|
||
singbox_manager.stop()
|
||
except Exception:
|
||
pass
|
||
|
||
chain_result: dict[str, Any] = {"skipped": True}
|
||
if mode == "shellcrash":
|
||
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:
|
||
# Normal ShellCrash node (not residential landing).
|
||
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 == "shellcrash" 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,
|
||
"proxychains_conf": pc_path,
|
||
"neko": neko_result,
|
||
}
|
||
|
||
|
||
def probe(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
mode = get_mode(cfg)
|
||
proxy = _host_http_proxy(cfg) if mode != "off" else ""
|
||
targets = [
|
||
("google", "https://www.google.com/generate_204"),
|
||
("youtube", "https://www.youtube.com/"),
|
||
("douyin", "https://www.douyin.com/"),
|
||
]
|
||
rows = []
|
||
for name, url in targets:
|
||
# Douyin: always probe DIRECT; also via proxy to show rule should still work for pull via ShellCrash
|
||
if name == "douyin":
|
||
rows.append(_curl_probe("douyin_direct", url, proxy=""))
|
||
if proxy:
|
||
rows.append(_curl_probe("douyin_via_sc", url, proxy=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 status(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
from . import shellcrash_hub
|
||
|
||
s = _settings(cfg)
|
||
mode = get_mode(s)
|
||
chain = chain_residential(s) if mode == "shellcrash" else False
|
||
sc = shellcrash_hub.status()
|
||
host_proxy = _host_http_proxy(s)
|
||
neko_proxy = neko_browser_proxy(s)
|
||
pc = proxychains_bin()
|
||
exit_label = RESIDENTIAL_PROXY_NAME if chain else (sc.get("selected_node") or shellcrash_hub.DEFAULT_NODE)
|
||
return {
|
||
"mode": mode,
|
||
"chain_residential": chain,
|
||
"modes": [
|
||
{"id": "off", "label": "直连", "description": "不经 ShellCrash"},
|
||
{
|
||
"id": "shellcrash",
|
||
"label": "ShellCrash",
|
||
"description": "业务统一走本机 :7890;可选住宅链式落地",
|
||
"ready": bool(sc.get("running") or sc.get("installed")),
|
||
},
|
||
],
|
||
"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": f"socks5://127.0.0.1:{shellcrash_mixed_port(s)}" if mode == "shellcrash" else "",
|
||
"proxychains": {
|
||
"installed": bool(pc),
|
||
"bin": pc,
|
||
"conf": str(PROXYCHAINS_CONF) if PROXYCHAINS_CONF.is_file() else "",
|
||
"relay_active": ffmpeg_uses_proxy(s),
|
||
},
|
||
"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",
|
||
"active": bool(neko_proxy),
|
||
"detail": (neko_proxy + (f" → {exit_label}" if chain else "")) if neko_proxy else "直连",
|
||
},
|
||
{
|
||
"id": "relay",
|
||
"label": "直播推流 FFmpeg",
|
||
"active": ffmpeg_uses_proxy(s),
|
||
"detail": (
|
||
f"proxychains → ShellCrash → {exit_label}"
|
||
if ffmpeg_uses_proxy(s)
|
||
else ("缺 proxychains" if cover_relay(s) and not pc else "直连")
|
||
),
|
||
},
|
||
{
|
||
"id": "uploads",
|
||
"label": "Shorts / 长视频 / 上传",
|
||
"active": bool(resolve_upload_proxy(s)),
|
||
"detail": (host_proxy + (f" → {exit_label}" if chain else "")) if resolve_upload_proxy(s) else "直连",
|
||
},
|
||
],
|
||
"hints": _hints(mode, chain, sc, pc),
|
||
"app_root": str(ROOT),
|
||
"backend": str(BACKEND),
|
||
}
|
||
|
||
|
||
def _hints(mode: str, chain: bool, sc: dict[str, Any], pc: str) -> list[str]:
|
||
out: list[str] = []
|
||
if mode == "shellcrash":
|
||
out.append("硬规则:*.douyin.com / 抖音 CDN 必须 DIRECT(拉流与监控不可走机场)")
|
||
if mode == "shellcrash" and not sc.get("running"):
|
||
out.append("ShellCrash 未运行 — 先启动,再应用出海")
|
||
if mode == "shellcrash" and chain:
|
||
out.append(
|
||
"住宅落地 = ShellCrash 链式(dialer-proxy):家宽 → 前置节点 → 住宅 SOCKS。"
|
||
"详见虚空终端 docs:dialer-proxy"
|
||
)
|
||
if mode == "shellcrash" and not chain:
|
||
out.append("当前用 ShellCrash 机场线路出海;勾选「住宅落地」才会链式到 SOCKS5")
|
||
if mode != "off" and not pc:
|
||
out.append("未安装 proxychains4 — 直播推流无法走代理")
|
||
if mode == "off":
|
||
out.append("直连:国内物理机上 YouTube Studio / 推流通常不可用")
|
||
return out
|