diff --git a/backend/app/downloads.py b/backend/app/downloads.py new file mode 100644 index 0000000..0799162 --- /dev/null +++ b/backend/app/downloads.py @@ -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) diff --git a/backend/app/main.py b/backend/app/main.py index 02352d7..98ad728 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -5,6 +5,7 @@ import csv import io import json import os +import subprocess import sys import time from contextlib import asynccontextmanager @@ -2177,6 +2178,41 @@ async def notify_test() -> dict[str, Any]: 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") async def rooms_export(format: str = Query("csv", pattern="^(csv|json)$")) -> Any: rows = db.export_rooms_rows() diff --git a/backend/app/s3_storage.py b/backend/app/s3_storage.py index 485a216..d8b187a 100644 --- a/backend/app/s3_storage.py +++ b/backend/app/s3_storage.py @@ -4,7 +4,7 @@ from __future__ import annotations import mimetypes from pathlib import Path -from typing import Optional +from typing import Any, Optional from urllib.parse import quote from .config import settings @@ -50,6 +50,26 @@ def public_url_for_key(key: str) -> str: 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: """Upload local file to SeaweedFS S3 API. Returns public URL.""" 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) +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: key = f"covers/{session_id}.jpg" return upload_file(local_path, key, content_type="image/jpeg") diff --git a/frontend/src/app/downloads/page.tsx b/frontend/src/app/downloads/page.tsx new file mode 100644 index 0000000..4d5cb5c --- /dev/null +++ b/frontend/src/app/downloads/page.tsx @@ -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(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 ( + +
+
+
+

⬇️ 下载中心

+

+ Chrome 安装包与最新插件构建,托管在本站 S3 + {data?.public_base ? `(${data.public_base}/${data.bucket})` : ""}。 +

+
+ +
+ + {!data?.s3_enabled ? ( +
+ S3 未启用:请检查 API 环境变量 DY_S3_*。 +
+ ) : null} + +
+ + + +
+ +
+ {items.map((it) => ( +
+
+
+

{it.title}

+

{it.description}

+
+ {it.filename} + {it.version ? ( + + v{it.version} + + ) : null} + {it.size_label || "—"} + 更新 {it.updated_at ? fmtTs(it.updated_at) : "—"} + + {it.available ? "可下载" : "尚未上传"} + +
+ {it.install_hint ? ( +

{it.install_hint}

+ ) : null} +
+
+ {it.available && it.url ? ( + + + 下载 + + ) : ( + + )} + {it.url ? ( + + ) : null} +
+
+ {it.url ? ( +

{it.url}

+ ) : null} +
+ ))} + {!loading && items.length === 0 ? ( +
+ 暂无下载项 +
+ ) : null} +
+
+
+ ); +} diff --git a/frontend/src/components/Shell.tsx b/frontend/src/components/Shell.tsx index 2a817e0..d64900b 100644 --- a/frontend/src/components/Shell.tsx +++ b/frontend/src/components/Shell.tsx @@ -29,6 +29,7 @@ const NAV = [ { href: "/shorts", label: "Shorts", emoji: "📱" }, { href: "/tiktok", label: "TikTok", emoji: "🎵" }, { href: "/x", label: "X", emoji: "𝕏" }, + { href: "/downloads", label: "下载", emoji: "⬇️" }, { href: "/blacklist", label: "黑名单", emoji: "🚫" }, { href: "/settings", label: "设置", emoji: "⚙️" }, ]; diff --git a/scripts/_publish_downloads.py b/scripts/_publish_downloads.py new file mode 100644 index 0000000..7e7bbb9 --- /dev/null +++ b/scripts/_publish_downloads.py @@ -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())