from __future__ import annotations import asyncio import subprocess from pathlib import Path from .config import settings from . import db async def capture_cover(session_id: str, stream_url: str) -> str: 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 "" db.set_session_cover(session_id, str(out_path)) return str(out_path) return await asyncio.to_thread(_run) 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 "")) if path.is_file(): return path fallback = settings.covers_dir / f"{session_id}.jpg" return fallback if fallback.is_file() else None