feat(test1): 下载页 — Chrome与最新插件托管到S3

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-15 06:30:00 -05:00
parent de9dc95413
commit ec3cfc2c27
6 changed files with 663 additions and 1 deletions

313
backend/app/downloads.py Normal file
View File

@ -0,0 +1,313 @@
# -*- 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)

View File

@ -5,6 +5,7 @@ import csv
import io import io
import json import json
import os import os
import subprocess
import sys import sys
import time import time
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
@ -2177,6 +2178,41 @@ async def notify_test() -> dict[str, Any]:
return {"ok": True, "webhook": url} return {"ok": True, "webhook": url}
@app.get("/api/downloads")
async def downloads_catalog() -> dict[str, Any]:
from . import downloads as downloads_mod
return await _db(downloads_mod.catalog)
@app.post("/api/downloads/sync-chrome")
async def downloads_sync_chrome(force: bool = Query(False)) -> dict[str, Any]:
from . import downloads as downloads_mod
try:
return await asyncio.to_thread(downloads_mod.sync_chrome_installer, force=force)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
except Exception as exc:
raise HTTPException(500, f"同步 Chrome 失败: {exc}") from exc
@app.post("/api/downloads/publish-extension")
async def downloads_publish_extension() -> dict[str, Any]:
"""Build extensions/dylive-helper and upload latest zip to S3."""
from . import downloads as downloads_mod
try:
return await asyncio.to_thread(downloads_mod.build_and_publish_extension)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
except subprocess.CalledProcessError as exc:
tail = (exc.stderr or exc.stdout or str(exc))[-800:]
raise HTTPException(500, f"插件构建失败: {tail}") from exc
except Exception as exc:
raise HTTPException(500, f"发布插件失败: {exc}") from exc
@app.get("/api/rooms/export") @app.get("/api/rooms/export")
async def rooms_export(format: str = Query("csv", pattern="^(csv|json)$")) -> Any: async def rooms_export(format: str = Query("csv", pattern="^(csv|json)$")) -> Any:
rows = db.export_rooms_rows() rows = db.export_rooms_rows()

View File

@ -4,7 +4,7 @@ from __future__ import annotations
import mimetypes import mimetypes
from pathlib import Path from pathlib import Path
from typing import Optional from typing import Any, Optional
from urllib.parse import quote from urllib.parse import quote
from .config import settings from .config import settings
@ -50,6 +50,26 @@ def public_url_for_key(key: str) -> str:
return f"{base}/{bucket}/{quote(key, safe='/')}" return f"{base}/{bucket}/{quote(key, safe='/')}"
def head_object(key: str) -> dict[str, Any] | None:
"""Return size / etag / last_modified for a key, or None if missing."""
if not s3_enabled():
return None
try:
client = _client()
resp = client.head_object(Bucket=settings.s3_bucket, Key=key)
lm = resp.get("LastModified")
return {
"key": key,
"size": int(resp.get("ContentLength") or 0),
"etag": str(resp.get("ETag") or "").strip('"'),
"content_type": str(resp.get("ContentType") or ""),
"last_modified": float(lm.timestamp()) if lm is not None else 0.0,
"url": public_url_for_key(key),
}
except Exception:
return None
def upload_file(local_path: str | Path, key: str, content_type: str = "") -> str: def upload_file(local_path: str | Path, key: str, content_type: str = "") -> str:
"""Upload local file to SeaweedFS S3 API. Returns public URL.""" """Upload local file to SeaweedFS S3 API. Returns public URL."""
path = Path(local_path) path = Path(local_path)
@ -69,6 +89,25 @@ def upload_file(local_path: str | Path, key: str, content_type: str = "") -> str
return public_url_for_key(key) return public_url_for_key(key)
def upload_bytes(data: bytes, key: str, content_type: str = "application/octet-stream") -> str:
if not data or not s3_enabled():
return ""
ensure_bucket()
client = _client()
ctype = content_type or "application/octet-stream"
try:
client.put_object(
Bucket=settings.s3_bucket,
Key=key,
Body=data,
ContentType=ctype,
ACL="public-read",
)
except Exception:
client.put_object(Bucket=settings.s3_bucket, Key=key, Body=data, ContentType=ctype)
return public_url_for_key(key)
def upload_cover(session_id: str, local_path: str | Path) -> str: def upload_cover(session_id: str, local_path: str | Path) -> str:
key = f"covers/{session_id}.jpg" key = f"covers/{session_id}.jpg"
return upload_file(local_path, key, content_type="image/jpeg") return upload_file(local_path, key, content_type="image/jpeg")

View File

@ -0,0 +1,215 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { Download, Loader2, Package, RefreshCw, Chrome } from "lucide-react";
import { Shell } from "@/components/Shell";
import { useToast } from "@/components/Toast";
import { fetchJson, fmtTs } from "@/lib/api";
type DownloadItem = {
id: string;
title: string;
kind: string;
filename: string;
description?: string;
version?: string;
install_hint?: string;
url: string;
size: number;
size_label?: string;
updated_at?: number;
available?: boolean;
};
type Catalog = {
s3_enabled?: boolean;
public_base?: string;
bucket?: string;
items?: DownloadItem[];
chrome_source?: string;
};
export default function DownloadsPage() {
const toast = useToast();
const [data, setData] = useState<Catalog | null>(null);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState("");
const load = useCallback(async () => {
setLoading(true);
try {
const r = await fetchJson("/api/downloads");
setData(r);
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setLoading(false);
}
}, [toast]);
useEffect(() => {
void load();
}, [load]);
async function syncChrome(force = false) {
setBusy(force ? "chrome-force" : "chrome");
try {
const r = await fetchJson(`/api/downloads/sync-chrome?force=${force ? "true" : "false"}`, {
method: "POST",
});
toast.push(r.skipped ? "Chrome 已在 S3,跳过下载" : "Chrome 已同步到 S3", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy("");
}
}
async function publishExt() {
setBusy("ext");
try {
const r = await fetchJson("/api/downloads/publish-extension", { method: "POST" });
toast.push(`插件 v${r.version || "?"} 已发布到 S3`, "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy("");
}
}
const items = data?.items || [];
return (
<Shell>
<div className="mx-auto max-w-4xl px-4 py-6 sm:px-6">
<div className="mb-5 flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">⬇️ 下载中心</h2>
<p className="mt-1 text-sm text-slate-400">
Chrome 安装包与最新插件构建,托管在本站 S3
{data?.public_base ? `(${data.public_base}/${data.bucket})` : ""}。
</p>
</div>
<button
type="button"
onClick={() => void load()}
className="inline-flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
</div>
{!data?.s3_enabled ? (
<div className="mb-4 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm text-amber-50">
S3 未启用:请检查 API 环境变量 <code className="text-amber-100">DY_S3_*</code>。
</div>
) : null}
<div className="mb-4 flex flex-wrap gap-2">
<button
type="button"
disabled={Boolean(busy) || !data?.s3_enabled}
onClick={() => void syncChrome(false)}
className="inline-flex items-center gap-1.5 rounded-xl border border-sky-500/30 bg-sky-500/10 px-3 py-2 text-xs text-sky-100 disabled:opacity-50"
>
{busy.startsWith("chrome") ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Chrome className="h-3.5 w-3.5" />}
同步 Chrome 到 S3
</button>
<button
type="button"
disabled={Boolean(busy) || !data?.s3_enabled}
onClick={() => void syncChrome(true)}
className="inline-flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-300 disabled:opacity-50"
>
强制重下 Chrome
</button>
<button
type="button"
disabled={Boolean(busy) || !data?.s3_enabled}
onClick={() => void publishExt()}
className="inline-flex items-center gap-1.5 rounded-xl border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-xs text-teal-100 disabled:opacity-50"
>
{busy === "ext" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Package className="h-3.5 w-3.5" />}
构建并发布最新插件
</button>
</div>
<div className="space-y-3">
{items.map((it) => (
<section
key={it.id}
className="rounded-2xl border border-white/10 bg-gradient-to-br from-white/[0.05] to-transparent p-4"
>
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<h3 className="text-base font-semibold text-white">{it.title}</h3>
<p className="mt-1 text-xs text-slate-400">{it.description}</p>
<div className="mt-2 flex flex-wrap gap-2 text-[11px] text-slate-500">
<span className="rounded border border-white/10 bg-black/30 px-2 py-0.5">{it.filename}</span>
{it.version ? (
<span className="rounded border border-teal-500/20 bg-teal-500/10 px-2 py-0.5 text-teal-200">
v{it.version}
</span>
) : null}
<span>{it.size_label || "—"}</span>
<span>更新 {it.updated_at ? fmtTs(it.updated_at) : "—"}</span>
<span className={it.available ? "text-emerald-300" : "text-rose-300"}>
{it.available ? "可下载" : "尚未上传"}
</span>
</div>
{it.install_hint ? (
<p className="mt-2 text-[11px] leading-relaxed text-slate-500">{it.install_hint}</p>
) : null}
</div>
<div className="flex shrink-0 flex-col gap-2">
{it.available && it.url ? (
<a
href={it.url}
target="_blank"
rel="noreferrer"
className="inline-flex items-center justify-center gap-1.5 rounded-xl bg-gradient-to-br from-teal-400 to-cyan-500 px-4 py-2 text-sm font-semibold text-[#041018]"
>
<Download className="h-4 w-4" />
下载
</a>
) : (
<button
type="button"
disabled
className="rounded-xl border border-white/10 px-4 py-2 text-sm text-slate-500"
>
暂无文件
</button>
)}
{it.url ? (
<button
type="button"
className="rounded-lg border border-white/10 px-2 py-1 text-[10px] text-slate-400 hover:bg-white/5"
onClick={() =>
void navigator.clipboard.writeText(it.url).then(() => toast.push("已复制下载链接", "ok"))
}
>
复制链接
</button>
) : null}
</div>
</div>
{it.url ? (
<p className="mt-3 break-all font-mono text-[10px] text-slate-600">{it.url}</p>
) : null}
</section>
))}
{!loading && items.length === 0 ? (
<div className="rounded-xl border border-dashed border-white/10 py-10 text-center text-sm text-slate-500">
暂无下载项
</div>
) : null}
</div>
</div>
</Shell>
);
}

View File

@ -29,6 +29,7 @@ const NAV = [
{ href: "/shorts", label: "Shorts", emoji: "📱" }, { href: "/shorts", label: "Shorts", emoji: "📱" },
{ href: "/tiktok", label: "TikTok", emoji: "🎵" }, { href: "/tiktok", label: "TikTok", emoji: "🎵" },
{ href: "/x", label: "X", emoji: "𝕏" }, { href: "/x", label: "X", emoji: "𝕏" },
{ href: "/downloads", label: "下载", emoji: "⬇️" },
{ href: "/blacklist", label: "黑名单", emoji: "🚫" }, { href: "/blacklist", label: "黑名单", emoji: "🚫" },
{ href: "/settings", label: "设置", emoji: "⚙️" }, { href: "/settings", label: "设置", emoji: "⚙️" },
]; ];

View File

@ -0,0 +1,58 @@
# -*- coding: utf-8 -*-
"""Build latest Chrome extension + sync Chrome installer to S3.
Usage (on server or local with DY_S3_* env):
python scripts/_publish_downloads.py
python scripts/_publish_downloads.py --chrome-only
python scripts/_publish_downloads.py --ext-only
python scripts/_publish_downloads.py --force-chrome
"""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "backend"))
os.chdir(ROOT / "backend")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--chrome-only", action="store_true")
parser.add_argument("--ext-only", action="store_true")
parser.add_argument("--force-chrome", action="store_true")
args = parser.parse_args()
from app import downloads
from app import s3_storage
from app.config import settings
if not s3_storage.s3_enabled():
print("S3 disabled — set DY_S3_ENABLED / DY_S3_ENDPOINT / DY_S3_PUBLIC_BASE / DY_S3_BUCKET")
return 1
print("public base:", settings.s3_public_base or settings.s3_endpoint)
print("bucket:", settings.s3_bucket)
if not args.ext_only:
print("=== sync Chrome ===")
r = downloads.sync_chrome_installer(force=args.force_chrome)
print(r)
if not args.chrome_only:
print("=== build + publish extension ===")
r = downloads.build_and_publish_extension()
print({k: r.get(k) for k in ("ok", "version", "latest_url", "version_url", "size")})
print("=== catalog ===")
cat = downloads.catalog()
for it in cat.get("items") or []:
print(f"- {it['id']}: available={it['available']} size={it['size_label']} url={it['url']}")
return 0
if __name__ == "__main__":
raise SystemExit(main())