File size: 8,789 Bytes
c075a93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40b1a3b
 
 
 
 
 
 
c075a93
40b1a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c075a93
40b1a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c075a93
 
40b1a3b
 
 
 
 
 
c075a93
40b1a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c075a93
40b1a3b
 
 
 
 
 
c075a93
 
 
 
 
 
 
 
 
 
 
 
40b1a3b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
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


def _is_redirect_url(url: str) -> bool:
    """Returns True for URLs that need pre-downloading (GDrive, etc.)."""
    return (
        "drive.google.com" in url
        or "drive.usercontent.google.com" in url
        or "docs.google.com" in url
    )


def _download_to_tempfile(url: str, dest_dir: Path) -> Path:
    """
    Download URL to a temp file in dest_dir.
    Handles GDrive confirmation pages automatically.
    Returns the temp file path.
    """
    import requests
    import tempfile

    session = requests.Session()
    headers = {"User-Agent": "Mozilla/5.0 (compatible; ffprobe/1.0)"}

    resp = session.get(url, headers=headers, stream=True, timeout=120, allow_redirects=True)
    resp.raise_for_status()

    # If GDrive returned HTML (virus-scan warning), grab the confirm token and retry
    content_type = resp.headers.get("content-type", "")
    if "text/html" in content_type:
        # Try to extract download warning form action / confirm param from HTML
        html = resp.content.decode(errors="replace")
        # Modern GDrive uses a "confirm" query param approach
        import re as _re
        match = _re.search(r'confirm=([0-9A-Za-z_\-]+)', html)
        if match:
            confirm = match.group(1)
            # Re-request with confirm token
            resp = session.get(
                url,
                headers=headers,
                params={"confirm": confirm},
                stream=True,
                timeout=120,
                allow_redirects=True,
            )
            resp.raise_for_status()
            content_type = resp.headers.get("content-type", "")

        if "text/html" in content_type:
            raise RuntimeError(
                f"URL returned HTML instead of media "
                f"(content-type: {content_type}). "
                f"Ensure the file is publicly shared and use a direct download URL."
            )

    # Detect extension from content-disposition or URL
    suffix = ".mp4"
    cd = resp.headers.get("content-disposition", "")
    if "filename=" in cd:
        fname = cd.split("filename=")[-1].strip().strip('"').split(";")[0].strip()
        ext = Path(fname).suffix
        if ext:
            suffix = ext
    elif "." in url.split("?")[0].split("/")[-1]:
        suffix = "." + url.split("?")[0].split("/")[-1].rsplit(".", 1)[-1]

    tmp = tempfile.NamedTemporaryFile(
        delete=False, suffix=suffix, dir=str(dest_dir)
    )
    for chunk in resp.iter_content(chunk_size=65536):
        if chunk:
            tmp.write(chunk)
    tmp.flush()
    tmp.close()

    tmp_path = Path(tmp.name)
    if tmp_path.stat().st_size == 0:
        tmp_path.unlink(missing_ok=True)
        raise RuntimeError("Downloaded file is 0 bytes β€” check file permissions/sharing settings.")

    return tmp_path


async def run_ffprobe(input_url: str, temp_dir: Optional[Path] = None) -> dict:
    """
    Return full ffprobe JSON for a URL or local path.
    GDrive and other redirect-heavy URLs are pre-downloaded first.
    """
    tmp_path: Optional[Path] = None
    probe_target = input_url

    try:
        if _is_redirect_url(input_url):
            td = temp_dir or Path("/tmp/frameforge")
            td.mkdir(parents=True, exist_ok=True)
            loop = asyncio.get_event_loop()
            tmp_path = await loop.run_in_executor(None, _download_to_tempfile, input_url, td)
            probe_target = str(tmp_path)

        cmd = [
            "ffprobe",
            "-v", "error",          # show errors (not quiet) so we get real messages
            "-print_format", "json",
            "-show_streams",
            "-show_format",
            "-show_error",
            probe_target,
        ]

        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=120)
        except asyncio.TimeoutError:
            proc.kill()
            raise RuntimeError("ffprobe timed out after 120s.")

        stdout_str = stdout.decode(errors="replace").strip()
        stderr_str = stderr.decode(errors="replace").strip()

        if proc.returncode != 0 or not stdout_str:
            raise RuntimeError(
                f"ffprobe failed (exit {proc.returncode}): "
                f"{stderr_str or 'no stderr output'}"
            )

        try:
            return json.loads(stdout_str)
        except json.JSONDecodeError as e:
            raise RuntimeError(
                f"ffprobe returned invalid JSON (exit {proc.returncode}): "
                f"{stderr_str}. JSON error: {e}"
            )

    finally:
        if tmp_path and tmp_path.exists():
            try:
                tmp_path.unlink()
            except Exception:
                pass


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"