douyinWEB/backend/app/cover.py
eric 11394a2a80 Document Pro relay/time-slot ops and harden relay worker stability.
README covers YouTube RTMPS relay, time-slot mode, ops/Netdata, and global SOCKS plan. Relay pipeline keeps FFmpeg alive across probe flicker, stabilizes time-slot source selection, and fixes misleading start-button copy in the UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:53:29 -05:00

273 lines
8.5 KiB
Python

# -*- coding: utf-8 -*-
from __future__ import annotations
import asyncio
import subprocess
from pathlib import Path
from typing import Any
from urllib.request import Request, urlopen
from . import db
from . import pb_sync
from . import s3_storage
from .config import settings
async def _sync_session_to_pb(session_id: str) -> None:
try:
session = db.get_session(session_id)
if session:
await pb_sync.sync_session(session)
except Exception:
pass
def _persist_cover_file(session_id: str, out_path: Path) -> str:
"""Persist cover bytes: S3 is required when enabled; local path only as last resort."""
if not out_path.is_file() or out_path.stat().st_size < 64:
return ""
stored = ""
if s3_storage.s3_enabled():
try:
public = s3_storage.upload_cover(session_id, out_path)
if public:
stored = public
except Exception:
stored = ""
if not stored:
# S3 required — do not pretend local path is the media store
return ""
else:
stored = str(out_path)
db.set_session_cover(session_id, stored)
return stored
async def capture_cover(session_id: str, stream_url: str) -> str:
"""Grab one frame via ffmpeg → upload S3 → write URL → sync PocketBase."""
url = (stream_url or "").strip()
if not url:
return ""
out_path = settings.covers_dir / f"{session_id}.jpg"
headers = (
"User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15\r\n"
"Referer: https://live.douyin.com/\r\n"
)
cmd = [
settings.ffmpeg_bin,
"-hide_banner",
"-loglevel",
"error",
"-y",
"-headers",
headers,
"-rw_timeout",
"15000000",
"-i",
url,
"-frames:v",
"1",
"-q:v",
"3",
str(out_path),
]
def _run() -> str:
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=25)
except Exception:
return ""
if proc.returncode != 0 or not out_path.is_file() or out_path.stat().st_size < 128:
return ""
return _persist_cover_file(session_id, out_path)
stored = await asyncio.to_thread(_run)
if stored:
await _sync_session_to_pb(session_id)
# optional: drop local file after S3 success to avoid disk fill
if s3_storage.s3_enabled():
try:
out_path.unlink(missing_ok=True)
except Exception:
pass
return stored
async def save_cover_from_image_url(session_id: str, image_url: str) -> str:
"""Download Douyin room cover / avatar → S3 → PocketBase."""
url = (image_url or "").strip()
if not url.startswith("http"):
return ""
out_path = settings.covers_dir / f"{session_id}.jpg"
def _run() -> str:
try:
req = Request(
url,
headers={
"User-Agent": (
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) "
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1"
),
"Referer": "https://live.douyin.com/",
"Accept": "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
},
)
with urlopen(req, timeout=15) as resp:
data = resp.read()
if not data or len(data) < 64:
return ""
out_path.write_bytes(data)
return _persist_cover_file(session_id, out_path)
except Exception:
return ""
stored = await asyncio.to_thread(_run)
if stored:
await _sync_session_to_pb(session_id)
if s3_storage.s3_enabled():
try:
out_path.unlink(missing_ok=True)
except Exception:
pass
return stored
async def ensure_room_avatar(
room_id: str,
avatar_image: str,
*,
force: bool = False,
) -> dict[str, Any]:
"""Mirror Douyin owner avatar → S3 covers/avatars/{room_id}.jpg → rooms.avatar_url + pool thumbs."""
rid = str(room_id or "").strip()
src = str(avatar_image or "").strip()
if not rid or not src.startswith("http"):
return {"ok": False, "error": "missing room_id or avatar_image"}
existing = ""
try:
room = db.get_room_by_room_id(rid)
existing = str((room or {}).get("avatar_url") or "").strip()
except Exception:
existing = ""
if existing.startswith("http") and not force:
return {"ok": True, "skipped": True, "avatar": existing}
out_path = settings.covers_dir / f"avatar_{rid}.jpg"
def _download_and_upload() -> str:
try:
req = Request(
src,
headers={
"User-Agent": (
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) "
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1"
),
"Referer": "https://live.douyin.com/",
"Accept": "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
},
)
with urlopen(req, timeout=15) as resp:
data = resp.read()
if not data or len(data) < 64:
return ""
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_bytes(data)
if not s3_storage.s3_enabled():
return ""
return s3_storage.upload_room_avatar(rid, out_path) or ""
except Exception:
return ""
stored = await asyncio.to_thread(_download_and_upload)
try:
out_path.unlink(missing_ok=True)
except Exception:
pass
if not stored or not (stored.startswith("http://") or stored.startswith("https://")):
return {
"ok": False,
"error": "s3 avatar upload failed",
"s3_enabled": s3_storage.s3_enabled(),
}
try:
db.set_room_avatar(rid, stored)
except Exception as exc:
return {"ok": False, "error": f"db: {exc}", "avatar": stored}
return {"ok": True, "avatar": stored, "s3": True}
async def ensure_session_cover(
session_id: str,
*,
stream_url: str = "",
cover_image: str = "",
prefer_stream: bool = True,
force: bool = False,
) -> dict[str, Any]:
"""
Ensure a session has a cover on S3 (+ PocketBase URL).
1) ffmpeg frame from live stream (best)
2) room cover / avatar image download (fallback)
"""
session = db.get_session(session_id)
if not session:
return {"ok": False, "error": "no session"}
existing = str(session.get("cover_path") or "").strip()
if not force and existing:
# still push to PB in case mirror lagged
await _sync_session_to_pb(session_id)
return {"ok": True, "skipped": True, "cover": existing}
path = ""
method = ""
if prefer_stream and stream_url:
path = await capture_cover(session_id, stream_url)
if path:
method = "stream"
if not path and cover_image:
path = await save_cover_from_image_url(session_id, cover_image)
if path:
method = "image"
if not path and (not prefer_stream) and stream_url:
path = await capture_cover(session_id, stream_url)
if path:
method = "stream"
if path:
return {"ok": True, "method": method, "cover": path, "s3": path.startswith("http")}
return {
"ok": False,
"error": "capture failed",
"had_stream": bool(stream_url),
"had_image": bool(cover_image),
"s3_enabled": s3_storage.s3_enabled(),
}
def cover_path_for(session_id: str) -> Path | None:
session = db.get_session(session_id)
if not session:
return None
raw = str(session.get("cover_path") or "")
if raw.startswith("http://") or raw.startswith("https://"):
return None
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 ""