import asyncio import json import re import shlex import subprocess from pathlib import Path from typing import Optional from models import FFmpegCommandRequest # ── 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"