Add SeaweedFS S3 covers and click-to-zoom lightbox.

Capture frames upload to SeaweedFS; active sessions show covers with enlarge preview.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-08 09:37:46 -05:00
parent 86bdcb9a21
commit d27387cb9e
10 changed files with 501 additions and 29 deletions

View File

@ -31,9 +31,18 @@ class Settings(BaseSettings):
error_backoff_base_sec: float = 60.0
error_backoff_max_sec: float = 600.0
global_pause_on_risk_sec: float = 90.0
capture_cover_on_start: bool = False
capture_cover_on_start: bool = True
ffmpeg_bin: str = "ffmpeg"
# SeaweedFS S3 API (open-source object storage with F)
s3_enabled: bool = False
s3_endpoint: str = "http://127.0.0.1:8333"
s3_public_base: str = "" # e.g. http://107.173.30.245:8333
s3_access_key: str = "douyin"
s3_secret_key: str = "douyinweb_s3_2026"
s3_bucket: str = "douyin-covers"
s3_region: str = "us-east-1"
class Config:
env_prefix = "DY_"
env_file = ".env"

View File

@ -1,14 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import asyncio
import subprocess
from pathlib import Path
from .config import settings
from . import db
from . import s3_storage
from .config import settings
async def capture_cover(session_id: str, stream_url: str) -> str:
"""Grab one frame via ffmpeg, optionally upload to SeaweedFS S3, persist URL/path."""
url = (stream_url or "").strip()
if not url:
return ""
@ -43,8 +46,16 @@ async def capture_cover(session_id: str, stream_url: str) -> str:
return ""
if proc.returncode != 0 or not out_path.is_file() or out_path.stat().st_size < 128:
return ""
db.set_session_cover(session_id, str(out_path))
return str(out_path)
stored = str(out_path)
if s3_storage.s3_enabled():
try:
public = s3_storage.upload_cover(session_id, out_path)
if public:
stored = public
except Exception:
pass
db.set_session_cover(session_id, stored)
return stored
return await asyncio.to_thread(_run)
@ -53,8 +64,20 @@ def cover_path_for(session_id: str) -> Path | None:
session = db.get_session(session_id)
if not session:
return None
path = Path(str(session.get("cover_path") or ""))
raw = str(session.get("cover_path") or "")
if raw.startswith("http://") or raw.startswith("https://"):
return None # remote URL — served via redirect/cover_url
path = Path(raw)
if path.is_file():
return path
fallback = settings.covers_dir / f"{session_id}.jpg"
return fallback if fallback.is_file() else None
def cover_public_url(session_id: str, cover_path: str = "") -> str:
raw = (cover_path or "").strip()
if raw.startswith("http://") or raw.startswith("https://"):
return raw
if raw or cover_path_for(session_id):
return f"/api/sessions/{session_id}/cover"
return ""

View File

@ -201,7 +201,11 @@ def _row_to_dict(row: sqlite3.Row | None) -> dict[str, Any] | None:
except json.JSONDecodeError:
data["meta"] = {}
if data.get("cover_path"):
data["cover_url"] = f"/api/sessions/{data['id']}/cover"
cp = str(data.get("cover_path") or "")
if cp.startswith("http://") or cp.startswith("https://"):
data["cover_url"] = cp
else:
data["cover_url"] = f"/api/sessions/{data['id']}/cover"
else:
if "cover_path" in data:
data["cover_url"] = ""

View File

@ -454,12 +454,56 @@ async def sessions_detail(session_id: str) -> dict[str, Any]:
@app.get("/api/sessions/{session_id}/cover")
async def sessions_cover(session_id: str):
from fastapi.responses import RedirectResponse
session = db.get_session(session_id)
if not session:
raise HTTPException(404, "场次不存在")
cp = str(session.get("cover_path") or "")
if cp.startswith("http://") or cp.startswith("https://"):
return RedirectResponse(cp, status_code=302)
path = cover_path_for(session_id)
if not path:
raise HTTPException(404, "无截图")
return FileResponse(path, media_type="image/jpeg")
@app.post("/api/sessions/active/recapture-covers")
async def recapture_active_covers() -> dict[str, Any]:
"""Capture covers for all currently active sessions (and upload to SeaweedFS if enabled)."""
cfg = db.get_settings_map()
cookie = str(cfg.get("dy_cookie") or "")
proxy = str(cfg.get("http_proxy") or "").strip() or None
items = db.list_active_sessions()
ok = 0
fail = 0
results: list[dict[str, Any]] = []
for s in items:
room = db.get_room(str(s.get("room_pk") or ""))
if not room:
fail += 1
results.append({"id": s.get("id"), "ok": False, "error": "no room"})
continue
try:
probed = await check_room(room["url"], cookie=cookie, proxy=proxy)
stream_url = str(probed.get("stream_url") or "")
if not stream_url:
fail += 1
results.append({"id": s.get("id"), "ok": False, "error": "no stream"})
continue
path = await capture_cover(str(s["id"]), stream_url)
if path:
ok += 1
results.append({"id": s.get("id"), "ok": True, "cover": path})
else:
fail += 1
results.append({"id": s.get("id"), "ok": False, "error": "capture failed"})
except Exception as exc:
fail += 1
results.append({"id": s.get("id"), "ok": False, "error": str(exc)})
await asyncio.sleep(1.5)
return {"ok": ok, "fail": fail, "results": results}
@app.post("/api/sessions/{session_id}/recapture")
async def sessions_recapture(session_id: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
session = db.get_session(session_id)

74
backend/app/s3_storage.py Normal file
View File

@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
"""SeaweedFS S3-compatible object storage helper."""
from __future__ import annotations
import mimetypes
from pathlib import Path
from typing import Optional
from urllib.parse import quote
from .config import settings
def s3_enabled() -> bool:
return bool(settings.s3_enabled and settings.s3_endpoint and settings.s3_bucket)
def _client():
import boto3
from botocore.client import Config
return boto3.client(
"s3",
endpoint_url=settings.s3_endpoint.rstrip("/"),
aws_access_key_id=settings.s3_access_key or "any",
aws_secret_access_key=settings.s3_secret_key or "any",
region_name=settings.s3_region or "us-east-1",
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
def ensure_bucket() -> None:
if not s3_enabled():
return
client = _client()
bucket = settings.s3_bucket
try:
client.head_bucket(Bucket=bucket)
except Exception:
try:
client.create_bucket(Bucket=bucket)
except Exception:
# race / already exists
pass
def public_url_for_key(key: str) -> str:
base = (settings.s3_public_base or settings.s3_endpoint or "").rstrip("/")
bucket = settings.s3_bucket.strip("/")
# path-style: http://host:8333/bucket/key
return f"{base}/{bucket}/{quote(key, safe='/')}"
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)
if not path.is_file():
return ""
if not s3_enabled():
return ""
ensure_bucket()
ctype = content_type or mimetypes.guess_type(str(path))[0] or "application/octet-stream"
client = _client()
extra = {"ContentType": ctype, "ACL": "public-read"}
try:
client.upload_file(str(path), settings.s3_bucket, key, ExtraArgs=extra)
except Exception:
# some SeaweedFS builds ignore ACL
client.upload_file(str(path), settings.s3_bucket, key, ExtraArgs={"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")

View File

@ -5,3 +5,4 @@ pydantic==2.10.4
pydantic-settings==2.7.0
python-multipart==0.0.20
aiofiles==24.1.0
boto3==1.35.99

View File

@ -4,6 +4,7 @@ import { useCallback, useEffect, useState } from "react";
import { Loader2, RefreshCw } from "lucide-react";
import { Shell } from "@/components/Shell";
import { ImageLightbox } from "@/components/ImageLightbox";
import { fetchJson, fmtDuration, fmtTs } from "@/lib/api";
type Session = {
@ -93,19 +94,13 @@ export default function CoversPage() {
</div>
) : null}
{selected ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4" onClick={() => setSelected(null)}>
<div className="max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-2xl border border-white/10 bg-[#0b1626] p-5" onClick={(e) => e.stopPropagation()}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={`${selected.cover_url}?ts=${selected.started_at || 0}`} alt="" className="mx-auto max-h-[60vh] rounded-lg object-contain" />
<div className="mt-3 space-y-1 text-sm">
<div className="font-medium">{selected.anchor_name || "—"}</div>
<div className="font-mono text-xs text-cyan-300">{selected.source_url}</div>
<div className="text-slate-400">开播 {fmtTs(selected.started_at)} · 时长 {fmtDuration(selected.duration_seconds)}</div>
</div>
<button type="button" className="mt-4 text-sm text-slate-400 hover:text-white" onClick={() => setSelected(null)}>关闭</button>
</div>
</div>
{selected?.cover_url ? (
<ImageLightbox
src={`${selected.cover_url}?ts=${selected.started_at || 0}`}
title={selected.anchor_name || selected.room_id || "封面"}
subtitle={`${fmtTs(selected.started_at)} · ${fmtDuration(selected.duration_seconds)}`}
onClose={() => setSelected(null)}
/>
) : null}
</Shell>
);

View File

@ -8,6 +8,7 @@ import { Shell } from "@/components/Shell";
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
import { AnimatedNumber, LivePulse, StatTile } from "@/components/ui";
import { useToast } from "@/components/Toast";
import { ImageLightbox } from "@/components/ImageLightbox";
import { fetchJson, fmtTs } from "@/lib/api";
import { liveElapsed, useEventStream, useNow } from "@/lib/realtime";
@ -58,6 +59,7 @@ export default function HomePage() {
const [active, setActive] = useState<ActiveSession[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [lightbox, setLightbox] = useState<ActiveSession | null>(null);
const toast = useToast();
const now = useNow(1000);
const { connected, last, tick } = useEventStream(true);
@ -184,29 +186,46 @@ export default function HomePage() {
</div>
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{active.map((s) => (
<a
<div
key={s.id}
href={s.source_url || "#"}
target="_blank"
rel="noreferrer"
className="hover-lift flex items-center gap-3 rounded-xl border border-rose-500/20 bg-rose-500/5 px-3 py-2"
>
{s.cover_url ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={`${s.cover_url}?ts=${s.started_at || 0}`} alt="" className="h-12 w-8 rounded object-cover" />
<button
type="button"
onClick={() => setLightbox(s)}
className="shrink-0 overflow-hidden rounded ring-1 ring-white/10 transition hover:ring-rose-300/50"
title="点击放大"
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={`${s.cover_url}${s.cover_url.includes("?") ? "&" : "?"}ts=${s.started_at || 0}`}
alt=""
className="h-14 w-10 object-cover"
/>
</button>
) : (
<div className="flex h-12 w-8 items-center justify-center rounded bg-slate-900 text-[10px] text-slate-600">LIVE</div>
<div className="flex h-14 w-10 shrink-0 items-center justify-center rounded bg-slate-900 text-[10px] text-slate-600">LIVE</div>
)}
<div className="min-w-0 flex-1">
<a href={s.source_url || "#"} target="_blank" rel="noreferrer" className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-white">{s.anchor_name || s.room_id}</div>
<div className="font-mono text-xs text-rose-200">{liveElapsed(s.started_at, now)}</div>
</div>
</a>
</a>
</div>
))}
</div>
</section>
) : null}
{lightbox?.cover_url ? (
<ImageLightbox
src={`${lightbox.cover_url}${lightbox.cover_url.includes("?") ? "&" : "?"}ts=${lightbox.started_at || 0}`}
title={lightbox.anchor_name || lightbox.room_id || "封面"}
subtitle={lightbox.source_url}
onClose={() => setLightbox(null)}
/>
) : null}
{(liveRooms.length > 0 || events.length > 0) ? (
<div className="mb-6 overflow-hidden rounded-2xl border border-rose-500/20 bg-rose-500/5">
<div className="flex items-center gap-2 border-b border-white/5 px-4 py-2 text-xs text-rose-100/80">

View File

@ -0,0 +1,57 @@
"use client";
import { useEffect } from "react";
type Props = {
src: string;
title?: string;
subtitle?: string;
onClose: () => void;
};
export function ImageLightbox({ src, title, subtitle, onClose }: Props) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
window.removeEventListener("keydown", onKey);
document.body.style.overflow = prev;
};
}, [onClose]);
return (
<div
className="fixed inset-0 z-[80] flex items-center justify-center bg-black/80 p-4 backdrop-blur-sm"
onClick={onClose}
role="dialog"
aria-modal="true"
>
<div
className="relative max-h-[92vh] w-full max-w-3xl overflow-hidden rounded-2xl border border-white/10 bg-[#0b1220] shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between border-b border-white/5 px-4 py-3">
<div className="min-w-0">
<div className="truncate text-sm font-medium text-white">{title || "封面预览"}</div>
{subtitle ? <div className="truncate text-xs text-slate-400">{subtitle}</div> : null}
</div>
<button
type="button"
onClick={onClose}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200 hover:bg-white/10"
>
关闭 Esc
</button>
</div>
<div className="flex max-h-[80vh] items-center justify-center bg-black/40 p-3">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={src} alt={title || "cover"} className="max-h-[76vh] w-auto max-w-full rounded-lg object-contain" />
</div>
</div>
</div>
);
}

246
scripts/deploy_seaweedfs.py Normal file
View File

@ -0,0 +1,246 @@
# -*- coding: utf-8 -*-
"""Install SeaweedFS + deploy cover/S3/lightbox updates to VPS."""
from __future__ import annotations
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
APP = "/opt/douyinWEB"
GIT = "https://eric:Xiao4669805@gitea.dsx2020.com/eric/douyinWEB.git"
S3_PORT = 8333
ACCESS = "douyin"
SECRET = "douyinweb_s3_2026"
BUCKET = "douyin-covers"
WEED_VER = "3.80"
def run(c: paramiko.SSHClient, cmd: str, timeout: int = 900) -> tuple[int, str]:
print(f"\n$ {cmd[:240]}", flush=True)
_, out, _ = c.exec_command(cmd, timeout=timeout, get_pty=True)
text = out.read().decode("utf-8", errors="replace")
code = out.channel.recv_exit_status()
print(text[-5000:], flush=True)
print(f"[exit {code}]", flush=True)
return code, text
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=40, allow_agent=False, look_for_keys=False)
print("connected", flush=True)
# --- SeaweedFS ---
run(
c,
f"""
set -e
mkdir -p /opt/seaweedfs /data/seaweed/master /data/seaweed/volume /data/seaweed/filer /etc/seaweedfs
if [ ! -x /opt/seaweedfs/weed ]; then
cd /tmp
curl -fsSL -o weed.tgz "https://github.com/seaweedfs/seaweedfs/releases/download/{WEED_VER}/linux_amd64.tar.gz"
tar -xzf weed.tgz -C /opt/seaweedfs weed
chmod +x /opt/seaweedfs/weed
rm -f weed.tgz
fi
/opt/seaweedfs/weed version || true
cat >/etc/seaweedfs/s3.json <<'EOF'
{{
"identities": [
{{
"name": "douyin",
"credentials": [
{{"accessKey": "{ACCESS}", "secretKey": "{SECRET}"}}
],
"actions": ["Admin", "Read", "Write", "List", "Tagging"]
}}
]
}}
EOF
cat >/etc/systemd/system/seaweed-master.service <<'EOF'
[Unit]
Description=SeaweedFS Master
After=network.target
[Service]
ExecStart=/opt/seaweedfs/weed master -ip=127.0.0.1 -port=9333 -mdir=/data/seaweed/master
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
cat >/etc/systemd/system/seaweed-volume.service <<'EOF'
[Unit]
Description=SeaweedFS Volume
After=network.target seaweed-master.service
Requires=seaweed-master.service
[Service]
ExecStart=/opt/seaweedfs/weed volume -mserver=127.0.0.1:9333 -ip=127.0.0.1 -port=8080 -dir=/data/seaweed/volume -max=100
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
cat >/etc/systemd/system/seaweed-filer.service <<'EOF'
[Unit]
Description=SeaweedFS Filer
After=network.target seaweed-master.service seaweed-volume.service
[Service]
ExecStart=/opt/seaweedfs/weed filer -master=127.0.0.1:9333 -ip=127.0.0.1 -port=8888 -defaultReplicaPlacement=000
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
cat >/etc/systemd/system/seaweed-s3.service <<'EOF'
[Unit]
Description=SeaweedFS S3 API
After=network.target seaweed-filer.service
Requires=seaweed-filer.service
[Service]
ExecStart=/opt/seaweedfs/weed s3 -filer=127.0.0.1:8888 -ip.bind=0.0.0.0 -port={S3_PORT} -config=/etc/seaweedfs/s3.json
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable seaweed-master seaweed-volume seaweed-filer seaweed-s3
systemctl restart seaweed-master
sleep 2
systemctl restart seaweed-volume
sleep 2
systemctl restart seaweed-filer
sleep 2
systemctl restart seaweed-s3
sleep 3
systemctl is-active seaweed-master seaweed-volume seaweed-filer seaweed-s3
ss -lntp | grep -E ':9333|:8080|:8888|:{S3_PORT}' || true
""".strip(),
timeout=300,
)
# create bucket via weed shell / s3 api with aws cli or python
run(
c,
f"""
set -e
pip3 install -q boto3 || true
python3 - <<'PY'
import boto3
from botocore.client import Config
c=boto3.client('s3', endpoint_url='http://127.0.0.1:{S3_PORT}',
aws_access_key_id='{ACCESS}', aws_secret_access_key='{SECRET}',
region_name='us-east-1', config=Config(signature_version='s3v4', s3={{'addressing_style':'path'}}))
try:
c.create_bucket(Bucket='{BUCKET}')
print('bucket created')
except Exception as e:
print('bucket', e)
print(c.list_buckets())
PY
""".strip(),
)
# pull app + deps + build
run(
c,
f"""
set -e
cd {APP}
git remote set-url origin '{GIT}'
git fetch origin
git reset --hard origin/main
# next rewrite stay on 8014
cat > frontend/next.config.mjs <<'EOF'
/** @type {{import('next').NextConfig}} */
const nextConfig = {{
reactStrictMode: true,
async rewrites() {{
return [
{{ source: "/api/:path*", destination: "http://127.0.0.1:8014/api/:path*" }},
{{ source: "/covers/:path*", destination: "http://127.0.0.1:8014/covers/:path*" }},
];
}},
}};
export default nextConfig;
EOF
cd backend
. .venv/bin/activate
pip install -r requirements.txt
python - <<'PY'
from app import db
db.init_db()
db.update_settings_map({{"capture_cover_on_start": True}})
print('capture_cover_on_start', db.get_settings_map().get('capture_cover_on_start'))
PY
# inject SeaweedFS env into api unit
cat >/etc/systemd/system/douyinweb-api.service <<'EOF'
[Unit]
Description=DouyinWEB FastAPI
After=network.target douyinweb-pb.service seaweed-s3.service
[Service]
Type=simple
WorkingDirectory={APP}/backend
Environment=DY_PB_URL=http://127.0.0.1:8092
Environment=DY_S3_ENABLED=true
Environment=DY_S3_ENDPOINT=http://127.0.0.1:{S3_PORT}
Environment=DY_S3_PUBLIC_BASE=http://{HOST}:{S3_PORT}
Environment=DY_S3_ACCESS_KEY={ACCESS}
Environment=DY_S3_SECRET_KEY={SECRET}
Environment=DY_S3_BUCKET={BUCKET}
Environment=DY_S3_REGION=us-east-1
ExecStart={APP}/backend/.venv/bin/python -m uvicorn app.main:app --host 0.0.0.0 --port 8014
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
cd {APP}/frontend
npm install --no-fund --no-audit
npm run build
systemctl daemon-reload
systemctl restart douyinweb-api douyinweb-web
sleep 6
systemctl is-active douyinweb-api douyinweb-web seaweed-s3
curl -s --max-time 10 http://127.0.0.1:8014/api/health | head -c 400
echo
curl -s -o /dev/null -w 'web:%{{http_code}}\\n' --max-time 15 http://127.0.0.1:4014/
""".strip(),
timeout=1200,
)
# backfill covers for active rooms
run(
c,
"""
set -e
curl -s --max-time 300 -X POST http://127.0.0.1:8014/api/sessions/active/recapture-covers
echo
curl -s --max-time 10 http://127.0.0.1:8014/api/sessions/active | python3 -c "import sys,json; d=json.load(sys.stdin); print('active', d.get('total'));
[print(s.get('anchor_name'), s.get('cover_url','')[:80]) for s in (d.get('sessions') or [])[:8]]"
""".strip(),
timeout=400,
)
c.close()
print(f"\nUI http://{HOST}:4014/", flush=True)
print(f"S3 http://{HOST}:{S3_PORT}/{BUCKET}/", flush=True)
if __name__ == "__main__":
main()