# -*- 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_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 ""