douyinWEB/backend/app/downloads.py
eric ec3cfc2c27 feat(test1): 下载页 — Chrome与最新插件托管到S3
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-15 06:30:00 -05:00

314 lines
10 KiB
Python
Raw 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 -*-
"""Public download catalog: Chrome installer + latest Chrome extension on S3."""
from __future__ import annotations
import json
import shutil
import subprocess
import sys
import tempfile
import time
import zipfile
from pathlib import Path
from typing import Any
import httpx
from . import s3_storage
from .config import settings
# Stable S3 keys (path-style public URLs under bucket)
CHROME_KEY = "downloads/chrome/ChromeStandaloneSetup64.exe"
EXT_LATEST_KEY = "downloads/extension/dylive-helper-latest.zip"
EXT_META_KEY = "downloads/extension/dylive-helper-latest.json"
MANIFEST_KEY = "downloads/manifest.json"
# Official Google Chrome Windows 64-bit offline/standalone installer
CHROME_SOURCE_URL = "https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe"
REPO_ROOT = Path(__file__).resolve().parents[2]
EXT_DIR = REPO_ROOT / "extensions" / "dylive-helper"
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 = "",
meta: dict[str, Any] | None = None,
) -> 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)
if meta:
version = str(meta.get("version") or version or "")
if meta.get("built_at"):
try:
updated = max(updated, float(meta["built_at"]))
except Exception:
pass
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_ext_meta() -> dict[str, Any]:
if not s3_storage.s3_enabled():
return {}
head = s3_storage.head_object(EXT_META_KEY)
if not head:
# fall back to local manifest version
try:
local = json.loads((EXT_DIR / "manifest.json").read_text(encoding="utf-8"))
return {"version": str(local.get("version") or "")}
except Exception:
return {}
try:
client = s3_storage._client() # noqa: SLF001
obj = client.get_object(Bucket=settings.s3_bucket, Key=EXT_META_KEY)
raw = obj["Body"].read()
return json.loads(raw.decode("utf-8"))
except Exception:
try:
local = json.loads((EXT_DIR / "manifest.json").read_text(encoding="utf-8"))
return {"version": str(local.get("version") or "")}
except Exception:
return {}
def catalog() -> dict[str, Any]:
meta = _read_ext_meta()
items = [
_item(
id="chrome-win64",
title="Google Chrome(Windows 64 位离线安装包)",
kind="chrome",
key=CHROME_KEY,
filename="ChromeStandaloneSetup64.exe",
description="官方 Standalone 安装包,上传到本站 S3 后提供稳定下载地址。",
install_hint="下载后双击安装。适合新机或不方便访问 Google 的环境。",
),
_item(
id="dylive-helper",
title="dylive Helper 浏览器插件(最新构建)",
kind="extension",
key=EXT_LATEST_KEY,
filename="dylive-helper-latest.zip",
description="TikTok Cookie + X 运维插件。每次发布会覆盖 latest,并附带版本号。",
version=str(meta.get("version") or ""),
install_hint="解压 zip → Chrome 打开 chrome://extensions → 打开「开发者模式」→「加载已解压的扩展程序」→ 选解压后的文件夹。",
meta=meta,
),
]
return {
"s3_enabled": s3_storage.s3_enabled(),
"public_base": (settings.s3_public_base or settings.s3_endpoint or "").rstrip("/"),
"bucket": settings.s3_bucket,
"items": items,
"chrome_source": CHROME_SOURCE_URL,
}
def _write_manifest(items: list[dict[str, Any]]) -> str:
body = {
"updated_at": time.time(),
"items": [
{
"id": it.get("id"),
"url": it.get("url"),
"version": it.get("version"),
"size": it.get("size"),
"updated_at": it.get("updated_at"),
"filename": it.get("filename"),
}
for it in items
],
}
return s3_storage.upload_bytes(
json.dumps(body, ensure_ascii=False, indent=2).encode("utf-8"),
MANIFEST_KEY,
content_type="application/json",
)
def sync_chrome_installer(*, force: bool = False) -> dict[str, Any]:
"""Fetch official Chrome standalone installer and upload to S3."""
if not s3_storage.s3_enabled():
raise ValueError("S3 未启用")
existing = s3_storage.head_object(CHROME_KEY)
if existing and int(existing.get("size") or 0) > 1_000_000 and not force:
return {
"ok": True,
"skipped": True,
"reason": "already_present",
"url": existing.get("url"),
"size": existing.get("size"),
}
with tempfile.NamedTemporaryFile(suffix=".exe", delete=False) as tmp:
tmp_path = Path(tmp.name)
try:
with httpx.Client(timeout=300.0, follow_redirects=True, trust_env=False) as client:
with client.stream("GET", CHROME_SOURCE_URL) 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 < 1_000_000:
raise ValueError(f"Chrome 安装包异常过小({size} bytes)")
url = s3_storage.upload_file(
tmp_path,
CHROME_KEY,
content_type="application/vnd.microsoft.portable-executable",
)
if not url:
raise ValueError("上传 S3 失败")
cat = catalog()
_write_manifest(cat["items"])
return {"ok": True, "skipped": False, "url": url, "size": size, "key": CHROME_KEY}
finally:
try:
tmp_path.unlink(missing_ok=True)
except Exception:
pass
def _zip_extension_dist(dist: Path, zip_path: Path) -> None:
if zip_path.exists():
zip_path.unlink()
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for path in sorted(dist.rglob("*")):
if path.is_file():
zf.write(path, path.relative_to(dist).as_posix())
def build_extension_zip(*, out_dir: Path | None = None) -> dict[str, Any]:
"""npm build dylive-helper and zip dist/. Returns paths + version."""
if not EXT_DIR.is_dir():
raise ValueError(f"插件目录不存在: {EXT_DIR}")
manifest_path = EXT_DIR / "manifest.json"
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
version = str(manifest.get("version") or "0.0.0")
# ensure deps
npm = ["npm"]
shell = False
if sys.platform == "win32":
shell = True
node_modules = EXT_DIR / "node_modules"
if not node_modules.is_dir():
subprocess.run(
"npm ci" if shell else ["npm", "ci"],
cwd=str(EXT_DIR),
check=True,
capture_output=True,
text=True,
shell=shell,
)
build = subprocess.run(
"npm run build" if shell else ["npm", "run", "build"],
cwd=str(EXT_DIR),
check=True,
capture_output=True,
text=True,
shell=shell,
)
dist = EXT_DIR / "dist"
if not dist.is_dir() or not (dist / "manifest.json").is_file():
raise ValueError("插件 build 后缺少 dist/manifest.json")
work = Path(out_dir) if out_dir else Path(tempfile.mkdtemp(prefix="dylive-ext-"))
work.mkdir(parents=True, exist_ok=True)
zip_path = work / f"dylive-helper-{version}.zip"
_zip_extension_dist(dist, zip_path)
return {
"version": version,
"zip_path": str(zip_path),
"dist": str(dist),
"build_log_tail": (build.stdout or "")[-500:],
}
def publish_extension_zip(
zip_path: str | Path,
*,
version: str = "",
built_at: float | None = None,
) -> dict[str, Any]:
"""Upload a prebuilt extension zip to S3 as latest (+ versioned copy)."""
if not s3_storage.s3_enabled():
raise ValueError("S3 未启用")
path = Path(zip_path)
if not path.is_file():
raise ValueError("zip 文件不存在")
if not version:
try:
version = str(json.loads((EXT_DIR / "manifest.json").read_text(encoding="utf-8")).get("version") or "")
except Exception:
version = "unknown"
now = float(built_at or time.time())
latest_url = s3_storage.upload_file(path, EXT_LATEST_KEY, content_type="application/zip")
ver_key = f"downloads/extension/dylive-helper-{version}.zip"
ver_url = s3_storage.upload_file(path, ver_key, content_type="application/zip")
meta = {
"version": version,
"built_at": now,
"filename": "dylive-helper-latest.zip",
"latest_key": EXT_LATEST_KEY,
"version_key": ver_key,
"latest_url": latest_url,
"version_url": ver_url,
"size": path.stat().st_size,
}
s3_storage.upload_bytes(
json.dumps(meta, ensure_ascii=False, indent=2).encode("utf-8"),
EXT_META_KEY,
content_type="application/json",
)
cat = catalog()
_write_manifest(cat["items"])
return {"ok": True, **meta}
def build_and_publish_extension() -> dict[str, Any]:
work = Path(tempfile.mkdtemp(prefix="dylive-ext-pub-"))
try:
built = build_extension_zip(out_dir=work)
published = publish_extension_zip(built["zip_path"], version=built["version"])
return {**built, **published}
finally:
shutil.rmtree(work, ignore_errors=True)