feat: add config expander and Mihomo config builder
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
import yaml
|
||||
|
||||
PROXY_FIELDS = {
|
||||
"name", "type", "server", "port", "uuid", "password", "cipher",
|
||||
"alterId", "tls", "network", "ws-opts", "h2-opts", "http-opts",
|
||||
"grpc-opts", "reality-opts", "servername", "fingerprint", "flow",
|
||||
"udp", "skip-cert-verify", "sni", "username", "plugin", "plugin-opts",
|
||||
"client-fingerprint", "early-data-header-name", "smux",
|
||||
}
|
||||
|
||||
|
||||
def filter_proxy(proxy: dict) -> dict:
|
||||
return {k: v for k, v in proxy.items() if k in PROXY_FIELDS}
|
||||
|
||||
|
||||
def expand_config(base_yaml: str, provider_proxies: dict[str, list[dict]]) -> str:
|
||||
cfg = yaml.safe_load(base_yaml)
|
||||
|
||||
all_proxies = list(cfg.get("proxies") or [])
|
||||
provider_to_names: dict[str, list[str]] = {}
|
||||
|
||||
for provider_name, proxies in provider_proxies.items():
|
||||
filtered = [filter_proxy(p) for p in proxies]
|
||||
provider_to_names[provider_name] = [p["name"] for p in filtered]
|
||||
all_proxies.extend(filtered)
|
||||
|
||||
cfg["proxies"] = all_proxies
|
||||
|
||||
for group in cfg.get("proxy-groups") or []:
|
||||
if "use" in group:
|
||||
expanded: list[str] = []
|
||||
for pname in group.pop("use"):
|
||||
expanded.extend(provider_to_names.get(pname, []))
|
||||
group.setdefault("proxies", [])
|
||||
group["proxies"] = group["proxies"] + expanded
|
||||
|
||||
cfg.pop("proxy-providers", None)
|
||||
|
||||
return yaml.dump(cfg, allow_unicode=True, sort_keys=False)
|
||||
|
||||
|
||||
def build_mihomo_config(all_base_yamls: list[str], secret: str) -> str:
|
||||
providers: dict[str, dict] = {}
|
||||
|
||||
for base_yaml in all_base_yamls:
|
||||
try:
|
||||
cfg = yaml.safe_load(base_yaml) or {}
|
||||
for name, provider in (cfg.get("proxy-providers") or {}).items():
|
||||
if name not in providers:
|
||||
providers[name] = provider
|
||||
except yaml.YAMLError:
|
||||
continue
|
||||
|
||||
config: dict = {
|
||||
"external-controller": "0.0.0.0:9090",
|
||||
"secret": secret,
|
||||
"mixed-port": 7890,
|
||||
"allow-lan": False,
|
||||
}
|
||||
if providers:
|
||||
config["proxy-providers"] = providers
|
||||
|
||||
return yaml.dump(config, allow_unicode=True, sort_keys=False)
|
||||
Reference in New Issue
Block a user