import asyncio import json import re import shlex import subprocess from pathlib import Path from typing import Callable, Optional from models import FFmpegCommandRequest from progress import ProgressSnapshot # ── Security: block dangerous shell patterns ────────────────────────────────── _BLOCKED_RE = re.compile( r"""( \brm\b | \bmv\b | \bcp\b | \bchmod\b | \bchown\b | \bkill\b | \bsudo\b | \bsu\b | \bwget\b | \bcurl\b | \bpython | \bbash\b | \bsh\b | \benv\b | \bexec\b | ; | && | \|\| | \` | \$\( | \bdd\b | /dev/ | \beval\b | \bnc\b | >> | 2> | >\s*/ )""", re.VERBOSE | re.IGNORECASE, ) MAX_FILE_SIZE_BYTES = 500 * 1024 * 1024 # 500 MB def sanitize_ffmpeg_args(args: str) -> str: """Raise ValueError if args contain blocked shell patterns.""" if _BLOCKED_RE.search(args): raise ValueError( "Blocked pattern detected in ffmpeg_args. " "Shell operators, file deletion, and system commands are not allowed." ) return args async def run_ffmpeg_from_url( request: FFmpegCommandRequest, work_dir: Path, ) -> Path: """Download input from URL, run FFmpeg, return output path.""" sanitize_ffmpeg_args(request.ffmpeg_args) output_name = request.output_filename or f"output.{request.output_format}" output_path = work_dir / output_name cmd = [ "ffmpeg", "-y", "-i", request.input_url, *shlex.split(request.ffmpeg_args), str(output_path), ] proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=str(work_dir), ) try: stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=300) except asyncio.TimeoutError: proc.kill() raise RuntimeError("FFmpeg job timed out after 5 minutes.") if proc.returncode != 0: err = stderr.decode(errors="replace")[-2000:] # Last 2000 chars of stderr raise RuntimeError(f"FFmpeg exited with code {proc.returncode}:\n{err}") if not output_path.exists(): raise RuntimeError("FFmpeg completed but output file was not created.") return output_path async def run_ffmpeg_from_file( ffmpeg_args: str, input_path: Path, output_format: str, work_dir: Path, output_filename: Optional[str] = None, ) -> Path: """Run FFmpeg on a local uploaded file.""" sanitize_ffmpeg_args(ffmpeg_args) output_name = output_filename or f"output.{output_format}" output_path = work_dir / output_name cmd = [ "ffmpeg", "-y", "-i", str(input_path), *shlex.split(ffmpeg_args), str(output_path), ] proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=str(work_dir), ) try: stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=300) except asyncio.TimeoutError: proc.kill() raise RuntimeError("FFmpeg job timed out after 5 minutes.") if proc.returncode != 0: err = stderr.decode(errors="replace")[-2000:] raise RuntimeError(f"FFmpeg exited with code {proc.returncode}:\n{err}") if not output_path.exists(): raise RuntimeError("FFmpeg completed but output file was not created.") return output_path async def run_ffprobe(input_url: str) -> dict: """Return full ffprobe JSON for a URL.""" cmd = [ "ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-show_format", input_url, ] proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) try: stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=60) except asyncio.TimeoutError: proc.kill() raise RuntimeError("ffprobe timed out.") if proc.returncode != 0: err = stderr.decode(errors="replace") raise RuntimeError(f"ffprobe failed:\n{err}") return json.loads(stdout.decode()) def get_ffmpeg_version() -> str: """Get installed FFmpeg version string.""" try: result = subprocess.run( ["ffmpeg", "-version"], capture_output=True, text=True, timeout=5 ) first_line = result.stdout.splitlines()[0] return first_line # e.g. "ffmpeg version 6.0 ..." except Exception: return "unknown" # ── Progress parsing ────────────────────────────────────────────────────────── _TIME_RE = re.compile(r"time=(\d+):(\d+):(\d+)\.(\d+)") _SPEED_RE = re.compile(r"speed=\s*([\d.]+)x") _FPS_RE = re.compile(r"fps=\s*([\d.]+)") _BITRATE_RE = re.compile(r"bitrate=\s*([\d.]+)kb/s") _FRAME_RE = re.compile(r"frame=\s*(\d+)") def _parse_progress(line: str, duration_s: float = 0) -> ProgressSnapshot: snap = ProgressSnapshot() if m := _FRAME_RE.search(line): snap.frame = int(m.group(1)) if m := _TIME_RE.search(line): h, mi, s, ms = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)) snap.time_elapsed = h * 3600 + mi * 60 + s + ms / 100 if duration_s > 0: snap.percent = min(100.0, round(snap.time_elapsed / duration_s * 100, 1)) if m := _SPEED_RE.search(line): snap.speed = m.group(1) if m := _FPS_RE.search(line): snap.fps = m.group(1) if m := _BITRATE_RE.search(line): snap.bitrate = m.group(1) return snap async def _ffmpeg_progress( cmd: list[str], work_dir: Path, progress_cb: Optional[Callable[[ProgressSnapshot], None]] = None, duration_s: float = 0, timeout: int = 300, ) -> Path: proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=str(work_dir), ) stderr_lines: list[bytes] = [] assert proc.stderr is not None while True: line = await proc.stderr.readline() if not line: break stderr_lines.append(line) text = line.decode(errors="replace").strip() if progress_cb and ("time=" in text or "frame=" in text): progress_cb(_parse_progress(text, duration_s)) await proc.wait() if proc.returncode != 0: err = b"".join(stderr_lines).decode(errors="replace")[-2000:] raise RuntimeError(f"FFmpeg exited with code {proc.returncode}:\n{err}") output_path = cmd[-1] p = Path(output_path) if not p.exists(): raise RuntimeError("FFmpeg completed but output file was not created.") return p # ── Public API (aliases matching main.py expectations) ──────────────────────── async def probe(input_url: str) -> dict: return await run_ffprobe(input_url) async def run_from_url( request: FFmpegCommandRequest, work_dir: Path, job_id: str = "", progress_cb: Optional[Callable[[ProgressSnapshot], None]] = None, ) -> Path: sanitize_ffmpeg_args(request.ffmpeg_args) output_name = request.output_filename or f"output.{request.output_format}" output_path = work_dir / output_name cmd = [ "ffmpeg", "-y", "-i", request.input_url, *shlex.split(request.ffmpeg_args), str(output_path), ] return await _ffmpeg_progress(cmd, work_dir, progress_cb) async def run_from_url_multi( request: FFmpegCommandRequest, extra_urls: list[str], work_dir: Path, job_id: str = "", progress_cb: Optional[Callable[[ProgressSnapshot], None]] = None, ) -> Path: sanitize_ffmpeg_args(request.ffmpeg_args) output_name = request.output_filename or f"output.{request.output_format}" output_path = work_dir / output_name cmd = ["ffmpeg", "-y"] cmd += ["-i", request.input_url] for url in extra_urls: cmd += ["-i", url] cmd += shlex.split(request.ffmpeg_args) cmd.append(str(output_path)) return await _ffmpeg_progress(cmd, work_dir, progress_cb) async def run_from_file( ffmpeg_args: str, input_path: Path, output_format: str, work_dir: Path, job_id: str = "", progress_cb: Optional[Callable[[ProgressSnapshot], None]] = None, output_filename: Optional[str] = None, ) -> Path: sanitize_ffmpeg_args(ffmpeg_args) output_name = output_filename or f"output.{output_format}" output_path = work_dir / output_name cmd = [ "ffmpeg", "-y", "-i", str(input_path), *shlex.split(ffmpeg_args), str(output_path), ] return await _ffmpeg_progress(cmd, work_dir, progress_cb) async def run_from_file_multi( ffmpeg_args: str, input_path: Path, extra_paths: list[Path], output_format: str, work_dir: Path, job_id: str = "", progress_cb: Optional[Callable[[ProgressSnapshot], None]] = None, output_filename: Optional[str] = None, ) -> Path: sanitize_ffmpeg_args(ffmpeg_args) output_name = output_filename or f"output.{output_format}" output_path = work_dir / output_name cmd = ["ffmpeg", "-y"] cmd += ["-i", str(input_path)] for p in extra_paths: cmd += ["-i", str(p)] cmd += shlex.split(ffmpeg_args) cmd.append(str(output_path)) return await _ffmpeg_progress(cmd, work_dir, progress_cb)