douyinWEB/scripts/linux/shellcrash_tuic_guard.py
2026-09-13 22:10:49 -05:00

125 lines
4.1 KiB
Python

#!/usr/bin/env python3
"""Soft-guard: revert Clash selector off VLESS → TUIC. No DB/business changes."""
from __future__ import annotations
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
CONTROLLER = os.environ.get("DY_SHELLCRASH_CONTROLLER", "http://127.0.0.1:9999").rstrip("/")
DEFAULT_NODE = os.environ.get("DY_SHELLCRASH_DEFAULT_NODE", "1d2da142-singbox_tuic5")
ALLOW_VLESS = str(os.environ.get("DY_SHELLCRASH_ALLOW_VLESS", "") or "").strip().lower() in {
"1",
"true",
"yes",
"on",
}
INTERVAL = int(os.environ.get("DY_SHELLCRASH_GUARD_INTERVAL", "60") or "60")
COOLDOWN = int(os.environ.get("DY_SHELLCRASH_GUARD_COOLDOWN", "120") or "120")
STATE_DIR = os.environ.get("DY_SHELLCRASH_GUARD_STATE", "/run/douyinweb-shellcrash-guard")
_last_fix = 0.0
def log(msg: str) -> None:
print(f"[sc-tuic-guard] {msg}", flush=True)
def _http_json(url: str, *, method: str = "GET", body: dict | None = None, timeout: float = 4.0) -> dict:
data = None
headers = {}
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
raw = r.read().decode("utf-8", "replace")
return {"ok": True, "data": json.loads(raw) if raw else {}}
except Exception as exc:
return {"ok": False, "error": str(exc)}
def _is_vless(name: str) -> bool:
return "vless" in str(name or "").lower()
def _selector_now(proxies: dict) -> tuple[str | None, str | None]:
prefer_keys = ("🚀 节点选择", "GLOBAL", "PROXY", "节点选择")
for key in prefer_keys:
cur = (proxies.get(key) or {}).get("now")
if cur:
return key, str(cur)
for key, val in proxies.items():
if not isinstance(val, dict) or val.get("type") != "Selector":
continue
cur = val.get("now")
if cur and ("节点" in key or "Select" in key or key.upper() == "PROXY"):
return key, str(cur)
for key, val in proxies.items():
if isinstance(val, dict) and val.get("type") == "Selector" and val.get("now"):
return key, str(val.get("now"))
return None, None
def _select(node: str, proxies: dict) -> None:
groups = []
for key in ("🚀 节点选择", "GLOBAL", "PROXY"):
if key == "GLOBAL" or key in proxies:
groups.append(key)
for key, val in proxies.items():
if isinstance(val, dict) and val.get("type") == "Selector" and "节点" in key and key not in groups:
groups.append(key)
if not groups:
groups = ["GLOBAL"]
for g in groups:
enc = urllib.parse.quote(g, safe="")
_http_json(f"{CONTROLLER}/proxies/{enc}", method="PUT", body={"name": node}, timeout=4.0)
def guard_once() -> None:
global _last_fix
if ALLOW_VLESS:
return
listed = _http_json(f"{CONTROLLER}/proxies", timeout=4.0)
if not listed.get("ok"):
return
proxies = (listed.get("data") or {}).get("proxies") or {}
group, now = _selector_now(proxies)
if not now or not _is_vless(now):
return
now_ts = time.time()
if now_ts - _last_fix < COOLDOWN:
log(f"VLESS selected ({now}) cooldown skip")
return
log(f"VLESS selected ({group}={now}) -> revert to {DEFAULT_NODE}")
_select(DEFAULT_NODE, proxies)
_last_fix = now_ts
try:
os.makedirs(STATE_DIR, exist_ok=True)
with open(os.path.join(STATE_DIR, "fixes.log"), "a", encoding="utf-8") as f:
f.write(f"{int(now_ts)} {now} -> {DEFAULT_NODE}\n")
except Exception:
pass
def main() -> int:
once = len(sys.argv) > 1 and sys.argv[1] == "once"
if once:
guard_once()
return 0
log(f"interval={INTERVAL}s default={DEFAULT_NODE} allow_vless={int(ALLOW_VLESS)}")
while True:
try:
guard_once()
except Exception as exc:
log(f"WARN {exc}")
time.sleep(max(5, INTERVAL))
if __name__ == "__main__":
raise SystemExit(main() or 0)