Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

fix(api): harden local material uploads

YANG10247003abab1a18
diff --git a/app/controllers/v1/video.py b/app/controllers/v1/video.py
index 70943445..8fed8cff 100644
--- a/app/controllers/v1/video.py
+++ b/app/controllers/v1/video.py
@@ -31,6 +31,7 @@ from app.models.schema import (
VideoMaterialRetrieveResponse
)
from app.services import bgm as bgm_service
+from app.services import material_upload as material_upload_service
from app.services import state as sm
from app.services import task as tm
from app.utils import file_security, utils
@@ -382,7 +383,10 @@ def upload_bgm_file(request: Request, file: UploadFile = File(...)):
"/video_materials", response_model=VideoMaterialRetrieveResponse, summary="Retrieve local video materials"
)
def get_video_materials_list(request: Request):
- allowed_suffixes = ("mp4", "mov", "avi", "flv", "mkv", "jpg", "jpeg", "png")
+ allowed_suffixes = tuple(
+ extension.removeprefix(".")
+ for extension in material_upload_service.SUPPORTED_MATERIAL_EXTENSIONS
+ )
local_videos_dir = utils.storage_dir("local_videos", create=True)
files = []
for suffix in allowed_suffixes:
@@ -413,26 +417,36 @@ def get_video_materials_list(request: Request):
)
def upload_video_material_file(request: Request, file: UploadFile = File(...)):
request_id = base.get_task_id(request)
- safe_filename = _sanitize_upload_filename(file.filename, request_id)
- # check file ext
- allowed_suffixes = ("mp4", "mov", "avi", "flv", "mkv", "jpg", "jpeg", "png")
- suffix = pathlib.Path(safe_filename).suffix.lower().lstrip(".")
- # 按完整扩展名校验,既兼容 .MOV 这类大写后缀,也避免 photojpg 这种没有
- # 点号的文件名因为 endswith("jpg") 被误当成合法图片。
- if suffix in allowed_suffixes:
- local_videos_dir = utils.storage_dir("local_videos", create=True)
- save_path = os.path.join(local_videos_dir, safe_filename)
- # save file
- with open(save_path, "wb+") as buffer:
- # If the file already exists, it will be overwritten
- file.file.seek(0)
- buffer.write(file.file.read())
- response = {"file": safe_filename}
- return utils.get_response(200, response)
+ try:
+ # Keep accepting browser-supplied client paths, but persist an immutable
+ # UUID storage key so repeated names cannot overwrite queued task inputs.
+ safe_filename = _sanitize_upload_filename(file.filename, request_id)
+ stored_filename = material_upload_service.save_material_upload(
+ safe_filename, file.file
+ )
+ except material_upload_service.MaterialUploadError as exc:
+ logger.warning(
+ f"local material upload rejected: request_id={request_id}, "
+ f"error={str(exc)}"
+ )
+ raise HttpException(
+ task_id=request_id,
+ status_code=400,
+ message=f"{request_id}: {str(exc)}",
+ )
+ except material_upload_service.MaterialServiceError as exc:
+ logger.error(
+ f"local material upload failed: request_id={request_id}, "
+ f"error={str(exc)}"
+ )
+ raise HttpException(
+ task_id=request_id,
+ status_code=500,
+ message=f"{request_id}: local material validation is unavailable",
+ )
- raise HttpException(
- "", status_code=400, message=f"{request_id}: Only files with extensions {', '.join(allowed_suffixes)} can be uploaded"
- )
+ response = {"file": stored_filename}
+ return utils.get_response(200, response)
@router.get("/stream/{file_path:path}")
async def stream_video(request: Request, file_path: str):
diff --git a/app/services/material_upload.py b/app/services/material_upload.py
new file mode 100644
index 00000000..ddafb19f
--- /dev/null
+++ b/app/services/material_upload.py
@@ -0,0 +1,264 @@
+import os
+import subprocess
+import tempfile
+import warnings
+from pathlib import Path
+from typing import BinaryIO, Literal
+from uuid import uuid4
+
+from loguru import logger
+from PIL import Image, UnidentifiedImageError
+
+from app.utils import utils
+
+
+# Local materials are usually short clips. This matches Streamlit's default upload
+# limit while still placing an explicit server-side bound on direct API clients.
+MAX_VIDEO_MATERIAL_UPLOAD_BYTES = 200 * 1024 * 1024
+MAX_IMAGE_MATERIAL_UPLOAD_BYTES = 20 * 1024 * 1024
+MATERIAL_VALIDATION_TIMEOUT_SECONDS = 120
+
+SUPPORTED_VIDEO_EXTENSIONS = (".mp4", ".mov", ".avi", ".flv", ".mkv")
+SUPPORTED_IMAGE_EXTENSIONS = (".jpg", ".jpeg", ".png")
+SUPPORTED_MATERIAL_EXTENSIONS = (
+ *SUPPORTED_VIDEO_EXTENSIONS,
+ *SUPPORTED_IMAGE_EXTENSIONS,
+)
+
+_COPY_CHUNK_BYTES = 1024 * 1024
+_INTERNAL_UPLOAD_PREFIX = ".material-upload-"
+_IMAGE_FORMATS_BY_EXTENSION = {
+ ".jpg": frozenset({"JPEG"}),
+ ".jpeg": frozenset({"JPEG"}),
+ ".png": frozenset({"PNG"}),
+}
+
+
+class MaterialUploadError(ValueError):
+ """The uploaded material does not satisfy the file or media requirements."""
+
+
+class MaterialServiceError(RuntimeError):
+ """The server could not stage, validate, or persist an uploaded material."""
+
+
+def uploaded_material_dir(create: bool = True) -> str:
+ return utils.storage_dir("local_videos", create=create)
+
+
+def _remove_staged_file(file_path: str) -> None:
+ if not file_path or not os.path.exists(file_path):
+ return
+ try:
+ os.remove(file_path)
+ except OSError as exc:
+ logger.warning(
+ f"failed to remove staged local material: path={file_path}, "
+ f"error={str(exc)}"
+ )
+
+
+def _material_kind(filename: str) -> Literal["video", "image"]:
+ suffix = Path(filename).suffix.lower()
+ if suffix in SUPPORTED_VIDEO_EXTENSIONS:
+ return "video"
+ if suffix in SUPPORTED_IMAGE_EXTENSIONS:
+ return "image"
+
+ supported_formats = ", ".join(
+ extension.removeprefix(".") for extension in SUPPORTED_MATERIAL_EXTENSIONS
+ )
+ raise MaterialUploadError(
+ f"unsupported local material format; supported formats: {supported_formats}"
+ )
+
+
+def sanitize_material_filename(filename: str) -> str:
+ """Return a display-safe basename and reject malformed or unsupported names."""
+ safe_name = (filename or "").replace("\\", "/").split("/")[-1].strip()
+ if (
+ not safe_name
+ or safe_name in {".", ".."}
+ or len(safe_name) > 255
+ or any(ord(character) < 32 for character in safe_name)
+ or safe_name.lower().startswith(_INTERNAL_UPLOAD_PREFIX)
+ ):
+ raise MaterialUploadError("invalid local material filename")
+ _material_kind(safe_name)
+ return safe_name
+
+
+def _validate_image(file_path: str, extension: str) -> None:
+ try:
+ # Pillow protects against excessively large pixel dimensions. Treat its
+ # warning threshold as an upload error too, rather than only rejecting at
+ # the higher DecompressionBombError threshold.
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", Image.DecompressionBombWarning)
+ with Image.open(file_path) as image:
+ image_format = str(image.format or "").upper()
+ if image_format not in _IMAGE_FORMATS_BY_EXTENSION[extension]:
+ raise MaterialUploadError(
+ "uploaded image content does not match its file extension"
+ )
+ image.verify()
+ except MaterialUploadError:
+ raise
+ except (
+ Image.DecompressionBombError,
+ Image.DecompressionBombWarning,
+ UnidentifiedImageError,
+ OSError,
+ SyntaxError,
+ ValueError,
+ ) as exc:
+ raise MaterialUploadError(
+ "uploaded file must contain a valid JPEG or PNG image"
+ ) from exc
+
+
+def _validate_video(
+ file_path: str, timeout_seconds: int = MATERIAL_VALIDATION_TIMEOUT_SECONDS
+) -> None:
+ # FFmpeg treats a standalone image as a one-frame video stream. Reject images
+ # explicitly so renaming photo.jpg to photo.mp4 cannot bypass the media class.
+ try:
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", Image.DecompressionBombWarning)
+ with Image.open(file_path) as image:
+ image.verify()
+ except (Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
+ raise MaterialUploadError(
+ "uploaded file must contain a video, not an image"
+ ) from exc
+ except (UnidentifiedImageError, OSError, SyntaxError, ValueError):
+ pass
+ else:
+ raise MaterialUploadError("uploaded file must contain a video, not an image")
+
+ try:
+ decoded = subprocess.run(
+ [
+ utils.get_ffmpeg_binary(),
+ "-nostdin",
+ "-v",
+ "error",
+ "-xerror",
+ "-i",
+ file_path,
+ "-map",
+ "0:v:0",
+ "-f",
+ "null",
+ "-",
+ ],
+ capture_output=True,
+ timeout=timeout_seconds,
+ check=False,
+ )
+ except subprocess.TimeoutExpired as exc:
+ raise MaterialServiceError("FFmpeg material validation timed out") from exc
+ except OSError as exc:
+ raise MaterialServiceError(
+ "failed to run FFmpeg for material validation"
+ ) from exc
+ if decoded.returncode != 0:
+ raise MaterialUploadError(
+ "uploaded file must contain a completely decodable video stream"
+ )
+
+
+def _stage_material_upload(
+ filename: str, source: BinaryIO
+) -> tuple[str, Literal["video", "image"], str, int]:
+ safe_name = sanitize_material_filename(filename)
+ material_kind = _material_kind(safe_name)
+ maximum_bytes = (
+ MAX_VIDEO_MATERIAL_UPLOAD_BYTES
+ if material_kind == "video"
+ else MAX_IMAGE_MATERIAL_UPLOAD_BYTES
+ )
+ maximum_megabytes = maximum_bytes // (1024 * 1024)
+
+ try:
+ target_dir = uploaded_material_dir(create=True)
+ except OSError as exc:
+ raise MaterialServiceError("failed to prepare local material storage") from exc
+
+ temp_path = ""
+ total_bytes = 0
+ try:
+ try:
+ source.seek(0)
+ except (AttributeError, OSError) as exc:
+ raise MaterialUploadError("local material upload is not seekable") from exc
+
+ descriptor, temp_path = tempfile.mkstemp(
+ prefix=_INTERNAL_UPLOAD_PREFIX,
+ suffix=Path(safe_name).suffix.lower(),
+ dir=target_dir,
+ )
+ with os.fdopen(descriptor, "wb") as output:
+ while True:
+ chunk = source.read(_COPY_CHUNK_BYTES)
+ if not chunk:
+ break
+ if not isinstance(chunk, (bytes, bytearray, memoryview)):
+ raise MaterialUploadError("local material upload must be binary")
+ total_bytes += len(chunk)
+ if total_bytes > maximum_bytes:
+ raise MaterialUploadError(
+ f"{material_kind} material exceeds the "
+ f"{maximum_megabytes} MB limit"
+ )
+ output.write(chunk)
+ output.flush()
+ os.fsync(output.fileno())
+
+ if total_bytes == 0:
+ raise MaterialUploadError("local material file is empty")
+ return safe_name, material_kind, temp_path, total_bytes
+ except Exception as exc:
+ _remove_staged_file(temp_path)
+ if isinstance(exc, MaterialUploadError):
+ raise
+ if isinstance(exc, OSError):
+ raise MaterialServiceError("failed to stage local material upload") from exc
+ raise
+ finally:
+ try:
+ source.seek(0)
+ except (AttributeError, OSError):
+ pass
+
+
+def save_material_upload(filename: str, source: BinaryIO) -> str:
+ """Validate and atomically persist an uploaded local video or image."""
+ safe_name, material_kind, temp_path, total_bytes = _stage_material_upload(
+ filename, source
+ )
+ extension = Path(safe_name).suffix.lower()
+ stored_name = f"{uuid4().hex}{extension}"
+ target_path = os.path.join(os.path.dirname(temp_path), stored_name)
+
+ try:
+ if material_kind == "video":
+ _validate_video(temp_path)
+ else:
+ _validate_image(temp_path, extension)
+
+ try:
+ os.replace(temp_path, target_path)
+ except OSError as exc:
+ raise MaterialServiceError(
+ "failed to persist local material upload"
+ ) from exc
+ temp_path = ""
+ logger.info(
+ f"local material uploaded: original_name={safe_name}, "
+ f"stored_name={stored_name}, kind={material_kind}, "
+ f"size={total_bytes} bytes"
+ )
+ return stored_name
+ finally:
+ _remove_staged_file(temp_path)
diff --git a/test/services/test_controller_video.py b/test/services/test_controller_video.py
index 1ac5ea2c..f3b2998a 100644
--- a/test/services/test_controller_video.py
+++ b/test/services/test_controller_video.py
@@ -17,6 +17,7 @@ from app.controllers.v1 import video as video_controller
from app.models import const
from app.models.exception import HttpException
from app.models.schema import TaskDeletionResponse, TaskListResponse, TaskQueryResponse
+from app.services import material_upload
from app.services import state as sm
from app.utils import utils
@@ -439,32 +440,54 @@ class TestVideoControllerFiles(unittest.TestCase):
def test_upload_video_material_validates_complete_extension(self):
"""大写合法扩展名应接受,无点号伪扩展名应拒绝。"""
- with tempfile.TemporaryDirectory() as temp_dir:
- upload = SimpleNamespace(
- filename=r"C:\videos\clip.MOV",
- file=BytesIO(b"video"),
+ upload = SimpleNamespace(
+ filename=r"C:\videos\clip.MOV",
+ file=BytesIO(b"video"),
+ )
+ with patch.object(
+ material_upload,
+ "save_material_upload",
+ return_value="4fca18fce7344f3aa824777a40d45c8c.mov",
+ ) as save_material:
+ response = video_controller.upload_video_material_file(
+ self._request(), upload
)
- with patch.object(
- video_controller.utils,
- "storage_dir",
- return_value=temp_dir,
- ):
- response = video_controller.upload_video_material_file(
- self._request(), upload
- )
- self.assertEqual(response["data"]["file"], "clip.MOV")
- self.assertEqual(Path(temp_dir, "clip.MOV").read_bytes(), b"video")
+ self.assertEqual(
+ response["data"]["file"],
+ "4fca18fce7344f3aa824777a40d45c8c.mov",
+ )
+ save_material.assert_called_once_with("clip.MOV", upload.file)
- invalid_upload = SimpleNamespace(
- filename="photojpg",
- file=BytesIO(b"not-an-image"),
- )
+ invalid_upload = SimpleNamespace(
+ filename="photojpg",
+ file=BytesIO(b"not-an-image"),
+ )
+ with patch.object(
+ material_upload,
+ "save_material_upload",
+ side_effect=material_upload.MaterialUploadError("unsupported format"),
+ ):
with self.assertRaises(HttpException) as raised:
video_controller.upload_video_material_file(
self._request(), invalid_upload
)
- self.assertEqual(raised.exception.status_code, 400)
+ self.assertEqual(raised.exception.status_code, 400)
+
+ def test_upload_video_material_maps_service_failure_to_stable_500(self):
+ upload = SimpleNamespace(filename="clip.mp4", file=BytesIO(b"video"))
+ with patch.object(
+ material_upload,
+ "save_material_upload",
+ side_effect=material_upload.MaterialServiceError(
+ "C:\\sensitive\\storage is unavailable"
+ ),
+ ):
+ with self.assertRaises(HttpException) as raised:
+ video_controller.upload_video_material_file(self._request(), upload)
+
+ self.assertEqual(raised.exception.status_code, 500)
+ self.assertNotIn("sensitive", raised.exception.message)
def test_stream_video_returns_requested_bytes(self):
"""Range 响应的正文和 Content-Range 必须与计算出的区间一致。"""
diff --git a/test/services/test_material_upload.py b/test/services/test_material_upload.py
new file mode 100644
index 00000000..6c596328
--- /dev/null
+++ b/test/services/test_material_upload.py
@@ -0,0 +1,282 @@
+import io
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+from uuid import UUID
+
+from PIL import Image, UnidentifiedImageError
+
+from app.services import material_upload
+
+
+class _UnseekableUpload(io.BytesIO):
+ def seek(self, *args, **kwargs):
+ raise OSError("not seekable")
+
+
+class _TextUpload(io.BytesIO):
+ def read(self, *args, **kwargs):
+ return "not binary"
+
+
+def _image_bytes(image_format: str = "PNG") -> bytes:
+ output = io.BytesIO()
+ Image.new("RGB", (2, 2), color="red").save(output, format=image_format)
+ return output.getvalue()
+
+
+class TestMaterialUploadService(unittest.TestCase):
+ def test_sanitize_filename_strips_paths_and_validates_complete_extension(self):
+ self.assertEqual(
+ material_upload.sanitize_material_filename(r"C:\videos\clip.MOV"),
+ "clip.MOV",
+ )
+ self.assertEqual(
+ material_upload.sanitize_material_filename("../../images/photo.png"),
+ "photo.png",
+ )
+
+ for filename in ("", ".", "..", "photojpg", "clip.mp4\x00", "clip.exe"):
+ with self.subTest(filename=filename):
+ with self.assertRaises(material_upload.MaterialUploadError):
+ material_upload.sanitize_material_filename(filename)
+
+ def test_video_upload_is_chunked_validated_and_atomically_persisted(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ source = io.BytesIO(b"decodable-video-placeholder")
+ with (
+ patch.object(
+ material_upload, "uploaded_material_dir", return_value=temp_dir
+ ),
+ patch.object(material_upload, "_validate_video") as validate_video,
+ patch.object(
+ material_upload,
+ "uuid4",
+ return_value=UUID("4fca18fc-e734-4f3a-a824-777a40d45c8c"),
+ ),
+ patch.object(
+ material_upload.os, "replace", wraps=os.replace
+ ) as replace,
+ ):
+ stored_name = material_upload.save_material_upload("clip.MOV", source)
+
+ self.assertEqual(stored_name, "4fca18fce7344f3aa824777a40d45c8c.mov")
+ self.assertEqual(
+ Path(temp_dir, stored_name).read_bytes(),
+ b"decodable-video-placeholder",
+ )
+ validate_video.assert_called_once()
+ replace.assert_called_once()
+ self.assertEqual(source.tell(), 0)
+ self.assertFalse(
+ any(
+ name.startswith(".material-upload-")
+ for name in os.listdir(temp_dir)
+ )
+ )
+
+ def test_same_original_name_creates_immutable_storage_keys(self):
+ generated_uuids = [
+ UUID("11111111-1111-4111-8111-111111111111"),
+ UUID("22222222-2222-4222-8222-222222222222"),
+ ]
+ with tempfile.TemporaryDirectory() as temp_dir:
+ with (
+ patch.object(
+ material_upload, "uploaded_material_dir", return_value=temp_dir
+ ),
+ patch.object(material_upload, "_validate_video"),
+ patch.object(material_upload, "uuid4", side_effect=generated_uuids),
+ ):
+ first = material_upload.save_material_upload(
+ "shared.mp4", io.BytesIO(b"first")
+ )
+ second = material_upload.save_material_upload(
+ "shared.mp4", io.BytesIO(b"second")
+ )
+
+ self.assertNotEqual(first, second)
+ self.assertEqual(Path(temp_dir, first).read_bytes(), b"first")
+ self.assertEqual(Path(temp_dir, second).read_bytes(), b"second")
+
+ def test_image_upload_validates_content_and_extension(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ with patch.object(
+ material_upload, "uploaded_material_dir", return_value=temp_dir
+ ):
+ stored_name = material_upload.save_material_upload(
+ "photo.PNG", io.BytesIO(_image_bytes("PNG"))
+ )
+ with self.assertRaisesRegex(
+ material_upload.MaterialUploadError, "does not match"
+ ):
+ material_upload.save_material_upload(
+ "renamed.png", io.BytesIO(_image_bytes("JPEG"))
+ )
+ with self.assertRaisesRegex(
+ material_upload.MaterialUploadError, "valid JPEG or PNG"
+ ):
+ material_upload.save_material_upload(
+ "broken.jpg", io.BytesIO(b"not-an-image")
+ )
+
+ self.assertTrue(stored_name.endswith(".png"))
+ self.assertEqual(len(os.listdir(temp_dir)), 1)
+
+ def test_renamed_image_is_not_accepted_as_video(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ with (
+ patch.object(
+ material_upload, "uploaded_material_dir", return_value=temp_dir
+ ),
+ patch.object(material_upload.subprocess, "run") as run,
+ ):
+ with self.assertRaisesRegex(
+ material_upload.MaterialUploadError, "not an image"
+ ):
+ material_upload.save_material_upload(
+ "renamed.mp4", io.BytesIO(_image_bytes("JPEG"))
+ )
+
+ run.assert_not_called()
+ self.assertEqual(os.listdir(temp_dir), [])
+
+ def test_empty_unseekable_and_non_binary_uploads_are_cleaned_up(self):
+ invalid_sources = (
+ (io.BytesIO(b""), "file is empty"),
+ (_UnseekableUpload(b"video"), "not seekable"),
+ (_TextUpload(b"video"), "must be binary"),
+ )
+ for source, expected_error in invalid_sources:
+ with self.subTest(expected_error=expected_error):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ with patch.object(
+ material_upload,
+ "uploaded_material_dir",
+ return_value=temp_dir,
+ ):
+ with self.assertRaisesRegex(
+ material_upload.MaterialUploadError, expected_error
+ ):
+ material_upload.save_material_upload("clip.mp4", source)
+ self.assertEqual(os.listdir(temp_dir), [])
+ self.assertEqual(source.tell(), 0)
+
+ def test_per_media_size_limits_are_enforced_and_temp_files_removed(self):
+ cases = (
+ ("clip.mp4", "MAX_VIDEO_MATERIAL_UPLOAD_BYTES"),
+ ("photo.png", "MAX_IMAGE_MATERIAL_UPLOAD_BYTES"),
+ )
+ for filename, limit_name in cases:
+ with self.subTest(filename=filename):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ with (
+ patch.object(
+ material_upload,
+ "uploaded_material_dir",
+ return_value=temp_dir,
+ ),
+ patch.object(material_upload, limit_name, 4),
+ ):
+ with self.assertRaisesRegex(
+ material_upload.MaterialUploadError, "exceeds"
+ ):
+ material_upload.save_material_upload(
+ filename, io.BytesIO(b"12345")
+ )
+ self.assertEqual(os.listdir(temp_dir), [])
+
+ def test_validation_failure_and_storage_failure_remove_temp_files(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ with (
+ patch.object(
+ material_upload, "uploaded_material_dir", return_value=temp_dir
+ ),
+ patch.object(
+ material_upload,
+ "_validate_video",
+ side_effect=material_upload.MaterialUploadError("invalid video"),
+ ),
+ ):
+ with self.assertRaises(material_upload.MaterialUploadError):
+ material_upload.save_material_upload(
+ "clip.mp4", io.BytesIO(b"broken")
+ )
+ self.assertEqual(os.listdir(temp_dir), [])
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ with (
+ patch.object(
+ material_upload, "uploaded_material_dir", return_value=temp_dir
+ ),
+ patch.object(material_upload, "_validate_video"),
+ patch.object(
+ material_upload.os,
+ "replace",
+ side_effect=OSError("disk full"),
+ ),
+ ):
+ with self.assertRaises(material_upload.MaterialServiceError):
+ material_upload.save_material_upload(
+ "clip.mp4", io.BytesIO(b"video")
+ )
+ self.assertEqual(os.listdir(temp_dir), [])
+
+ def test_video_validation_uses_configured_ffmpeg_and_video_stream(self):
+ completed = SimpleNamespace(returncode=0)
+ with (
+ patch.object(
+ material_upload.Image,
+ "open",
+ side_effect=UnidentifiedImageError("not an image"),
+ ),
+ patch.object(
+ material_upload.utils,
+ "get_ffmpeg_binary",
+ return_value="/portable/imageio/ffmpeg",
+ ),
+ patch.object(
+ material_upload.subprocess, "run", return_value=completed
+ ) as run,
+ ):
+ material_upload._validate_video("/tmp/clip.mp4")
+
+ command = run.call_args.args[0]
+ self.assertEqual(command[0], "/portable/imageio/ffmpeg")
+ self.assertIn("0:v:0", command)
+ self.assertIn("-xerror", command)
+ self.assertNotIn("ffprobe", " ".join(command).lower())
+
+ def test_video_validation_distinguishes_invalid_media_from_tool_failure(self):
+ image_error = UnidentifiedImageError("not an image")
+ with patch.object(material_upload.Image, "open", side_effect=image_error):
+ with patch.object(
+ material_upload.subprocess,
+ "run",
+ return_value=SimpleNamespace(returncode=1),
+ ):
+ with self.assertRaises(material_upload.MaterialUploadError):
+ material_upload._validate_video("/tmp/clip.mp4")
+
+ with patch.object(
+ material_upload.subprocess,
+ "run",
+ side_effect=OSError("ffmpeg missing"),
+ ):
+ with self.assertRaises(material_upload.MaterialServiceError):
+ material_upload._validate_video("/tmp/clip.mp4")
+
+ with patch.object(
+ material_upload.subprocess,
+ "run",
+ side_effect=material_upload.subprocess.TimeoutExpired("ffmpeg", 120),
+ ):
+ with self.assertRaises(material_upload.MaterialServiceError):
+ material_upload._validate_video("/tmp/clip.mp4")
+
+
+if __name__ == "__main__":
+ unittest.main()