douyinWEB/backend/app/clash_dl.py
eric 744a35fbbd feat(test1): 新增 /clash 页托管 Clash Verge 与 clash.yaml
从 GitHub 同步 Win x64 安装包到 S3,并提供配置下载与同步 API。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-15 09:31:01 -05:00

250 lines
8.2 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 -*-
"""Clash Verge Rev installer + clash.yaml hosted on S3."""
from __future__ import annotations
import json
import re
import tempfile
import time
from pathlib import Path
from typing import Any
import httpx
from . import s3_storage
from .config import settings
CLASH_VERGE_KEY = "downloads/clash/Clash.Verge_x64-setup.exe"
CLASH_VERGE_META_KEY = "downloads/clash/Clash.Verge_x64-setup.json"
CLASH_YAML_KEY = "downloads/clash/clash.yaml"
CLASH_SOURCE_REPO = "clash-verge-rev/clash-verge-rev"
ASSETS_DIR = Path(__file__).resolve().parent / "clash_assets"
LOCAL_YAML = ASSETS_DIR / "clash.yaml"
def _fmt_size(n: int) -> str:
if n <= 0:
return "—"
units = ["B", "KB", "MB", "GB"]
v = float(n)
for u in units:
if v < 1024 or u == units[-1]:
return f"{v:.0f} {u}" if u == "B" else f"{v:.1f} {u}"
v /= 1024.0
return f"{n} B"
def _item(
*,
id: str,
title: str,
kind: str,
key: str,
filename: str,
description: str = "",
version: str = "",
install_hint: str = "",
) -> dict[str, Any]:
head = s3_storage.head_object(key) if s3_storage.s3_enabled() else None
available = bool(head and head.get("size", 0) > 0)
url = (head or {}).get("url") or (s3_storage.public_url_for_key(key) if s3_storage.s3_enabled() else "")
size = int((head or {}).get("size") or 0)
updated = float((head or {}).get("last_modified") or 0)
return {
"id": id,
"title": title,
"kind": kind,
"key": key,
"filename": filename,
"description": description,
"version": version,
"install_hint": install_hint,
"url": url,
"size": size,
"size_label": _fmt_size(size),
"updated_at": updated,
"available": available,
"etag": (head or {}).get("etag") or "",
}
def _read_meta() -> dict[str, Any]:
if not s3_storage.s3_enabled():
return {}
try:
client = s3_storage._client() # noqa: SLF001
obj = client.get_object(Bucket=settings.s3_bucket, Key=CLASH_VERGE_META_KEY)
return json.loads(obj["Body"].read().decode("utf-8"))
except Exception:
return {}
def _github_latest_x64_setup() -> dict[str, Any]:
api = f"https://api.github.com/repos/{CLASH_SOURCE_REPO}/releases/latest"
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "douyinWEB-clash-sync",
}
with httpx.Client(timeout=60.0, follow_redirects=True, trust_env=False, headers=headers) as client:
resp = client.get(api)
resp.raise_for_status()
data = resp.json()
tag = str(data.get("tag_name") or "").strip()
assets = data.get("assets") or []
# Prefer standard x64-setup.exe (not fixed_webview2 which is huge)
preferred = None
for a in assets:
name = str(a.get("name") or "")
if re.search(r"x64-setup\.exe$", name, re.I) and "fixed_webview2" not in name.lower():
preferred = a
break
if not preferred:
for a in assets:
name = str(a.get("name") or "")
if "x64" in name.lower() and name.lower().endswith(".exe") and "sig" not in name.lower():
preferred = a
break
if not preferred:
raise ValueError("GitHub release 中未找到 Windows x64 setup.exe")
url = str(preferred.get("browser_download_url") or "").strip()
if not url:
raise ValueError("缺少 browser_download_url")
return {
"tag": tag,
"name": str(preferred.get("name") or ""),
"url": url,
"size": int(preferred.get("size") or 0),
}
def catalog() -> dict[str, Any]:
meta = _read_meta()
ver = str(meta.get("version") or meta.get("tag") or "")
items = [
_item(
id="clash-verge-win64",
title="Clash Verge Rev(Windows x64 安装包)",
kind="installer",
key=CLASH_VERGE_KEY,
filename="Clash.Verge_x64-setup.exe",
description="来自 GitHub clash-verge-rev 正式版 x64-setup,托管到本站 S3。",
version=ver,
install_hint="下载后双击安装 → 打开 Clash Verge → 配置文件 → 导入下方 clash.yaml。",
),
_item(
id="clash-yaml",
title="clash.yaml 配置文件",
kind="config",
key=CLASH_YAML_KEY,
filename="clash.yaml",
description="本站维护的 mihomo/Clash Meta 规则配置(含节点与分流)。",
version="",
install_hint="下载后在 Clash Verge 中「导入」或放入配置目录后启用。",
),
]
return {
"s3_enabled": s3_storage.s3_enabled(),
"public_base": (settings.s3_public_base or settings.s3_endpoint or "").rstrip("/"),
"bucket": settings.s3_bucket,
"source_repo": f"https://github.com/{CLASH_SOURCE_REPO}",
"items": items,
"meta": meta,
}
def publish_clash_yaml() -> dict[str, Any]:
if not s3_storage.s3_enabled():
raise ValueError("S3 未启用")
if not LOCAL_YAML.is_file():
raise ValueError(f"本地配置不存在: {LOCAL_YAML}")
data = LOCAL_YAML.read_bytes()
if not data.strip():
raise ValueError("clash.yaml 为空")
url = s3_storage.upload_bytes(data, CLASH_YAML_KEY, content_type="text/yaml; charset=utf-8")
if not url:
raise ValueError("上传 clash.yaml 失败")
return {"ok": True, "url": url, "key": CLASH_YAML_KEY, "size": len(data)}
def sync_clash_verge_installer(*, force: bool = False) -> dict[str, Any]:
"""Fetch latest Clash Verge Rev Windows x64 setup from GitHub → S3."""
if not s3_storage.s3_enabled():
raise ValueError("S3 未启用")
release = _github_latest_x64_setup()
tag = str(release.get("tag") or "")
existing = s3_storage.head_object(CLASH_VERGE_KEY)
meta = _read_meta()
if (
existing
and int(existing.get("size") or 0) > 5_000_000
and not force
and str(meta.get("tag") or "") == tag
):
return {
"ok": True,
"skipped": True,
"reason": "already_present",
"tag": tag,
"url": existing.get("url"),
"size": existing.get("size"),
}
src = str(release["url"])
with tempfile.NamedTemporaryFile(suffix=".exe", delete=False) as tmp:
tmp_path = Path(tmp.name)
try:
headers = {"User-Agent": "douyinWEB-clash-sync", "Accept": "application/octet-stream"}
with httpx.Client(timeout=600.0, follow_redirects=True, trust_env=False, headers=headers) as client:
with client.stream("GET", src) as resp:
resp.raise_for_status()
with tmp_path.open("wb") as f:
for chunk in resp.iter_bytes(1024 * 256):
f.write(chunk)
size = tmp_path.stat().st_size
if size < 5_000_000:
raise ValueError(f"安装包异常过小({size} bytes)")
url = s3_storage.upload_file(
tmp_path,
CLASH_VERGE_KEY,
content_type="application/vnd.microsoft.portable-executable",
)
if not url:
raise ValueError("上传 S3 失败")
meta_body = {
"tag": tag,
"version": tag.lstrip("v"),
"source_name": release.get("name"),
"source_url": src,
"size": size,
"synced_at": time.time(),
"key": CLASH_VERGE_KEY,
"url": url,
}
s3_storage.upload_bytes(
json.dumps(meta_body, ensure_ascii=False, indent=2).encode("utf-8"),
CLASH_VERGE_META_KEY,
content_type="application/json",
)
yaml_res = publish_clash_yaml()
return {
"ok": True,
"skipped": False,
"tag": tag,
"url": url,
"size": size,
"key": CLASH_VERGE_KEY,
"yaml": yaml_res,
}
finally:
try:
tmp_path.unlink(missing_ok=True)
except Exception:
pass
def local_yaml_text() -> str:
if not LOCAL_YAML.is_file():
raise FileNotFoundError("clash.yaml 不存在")
return LOCAL_YAML.read_text(encoding="utf-8")