# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import subprocess from pathlib import Path 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 "" 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 "" 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) 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 # 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 ""