add local video upload API

This commit is contained in:
nstarikov 2026-08-15 11:23:45 +03:00
parent 116d54c43a
commit a3be5d07a8
2 changed files with 221 additions and 0 deletions

View file

@ -8,6 +8,7 @@ import os
from pathlib import Path
import random
import re
import shutil
import subprocess
from typing import Any
from uuid import uuid4
@ -50,6 +51,10 @@ ZEN_VERIFICATION_META = (
'content="y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouMOhtBECx6zgC5CCqVZRxslhhjSg" />'
)
PUBLIC_REDIRECT_URL = "https://nstarikov.ru"
ALLOWED_VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov", ".mkv"}
MAX_VIDEO_UPLOAD_BYTES = 10 * 1024 * 1024 * 1024
VIDEO_UPLOAD_CHUNK_BYTES = 1024 * 1024
VIDEO_UPLOAD_LOG_INTERVAL_BYTES = 5 * 1024 * 1024
class SourceIn(BaseModel):
@ -427,6 +432,46 @@ def local_video_file(video: Video, settings: Settings) -> Path | None:
return None
def video_storage_payload(settings: Settings) -> dict[str, int]:
settings.videos_path.mkdir(parents=True, exist_ok=True)
usage = shutil.disk_usage(settings.videos_path)
used_percent = round(usage.used / usage.total * 100) if usage.total else 0
free_percent = round(usage.free / usage.total * 100) if usage.total else 0
return {
"totalBytes": usage.total,
"usedBytes": usage.used,
"freeBytes": usage.free,
"usedPercent": used_percent,
"freePercent": free_percent,
}
def uploaded_video_duration(path: Path) -> int:
command = [
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
str(path),
]
try:
result = subprocess.run(command, capture_output=True, text=True, timeout=30, check=False)
duration = float(result.stdout.strip()) if result.returncode == 0 else 0
except (OSError, subprocess.TimeoutExpired, ValueError):
duration = 0
if duration <= 0:
raise HTTPException(status_code=422, detail="Не удалось определить длительность видео через ffprobe.")
return round(duration)
def upload_log_line(stage: str, message: str) -> str:
now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
return f"[{now}] {stage}: {message}"
def create_random_frame(video: Video, settings: Settings) -> tuple[Path, str, int]:
video_path = local_video_file(video, settings)
if not video_path:
@ -616,6 +661,111 @@ def import_video(payload: ManualVideoIn, session: Session = Depends(get_session)
}
@router.get("/api/storage/videos")
def video_storage(settings: Settings = Depends(get_settings)) -> dict[str, int]:
return video_storage_payload(settings)
@router.post("/api/videos/upload")
async def upload_video(
file: UploadFile = File(...),
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> dict[str, int | str | None]:
filename = Path(file.filename or "").name
suffix = Path(filename).suffix.lower()
if suffix not in ALLOWED_VIDEO_EXTENSIONS:
raise HTTPException(status_code=422, detail="Поддерживаются только MP4, WebM, MOV и MKV.")
settings.videos_path.mkdir(parents=True, exist_ok=True)
if shutil.disk_usage(settings.videos_path).free <= 0:
raise HTTPException(status_code=507, detail="На диске для видео нет свободного места.")
external_id = f"upload:{uuid4().hex}"
title = Path(filename).stem.strip() or "Загруженный ролик"
video = Video(
source_id=None,
external_id=external_id,
source_url=f"upload://{external_id}",
title=title,
description="",
published_at=datetime.now(timezone.utc),
status="new",
progress_percent=0,
progress_stage="Загрузка файла",
progress_log=upload_log_line("Загрузка", f"Начинаю прием файла: {filename}"),
)
session.add(video)
session.commit()
session.refresh(video)
root = settings.videos_path.resolve()
video_dir = (settings.videos_path / str(video.id)).resolve()
target = video_dir / f"video{suffix}"
bytes_written = 0
bytes_at_last_log = 0
declared_size = getattr(file, "size", None)
total_bytes = declared_size if isinstance(declared_size, int) and declared_size > 0 else None
try:
if not video_dir.is_relative_to(root):
raise RuntimeError("Небезопасный путь для загруженного видео.")
video_dir.mkdir(parents=True, exist_ok=False)
with target.open("xb") as output:
while chunk := await file.read(VIDEO_UPLOAD_CHUNK_BYTES):
next_size = bytes_written + len(chunk)
if next_size > MAX_VIDEO_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="Размер видео не должен превышать 10 ГБ.")
if len(chunk) > shutil.disk_usage(settings.videos_path).free:
raise HTTPException(status_code=507, detail="На диске для видео закончилось свободное место.")
output.write(chunk)
bytes_written = next_size
if bytes_written - bytes_at_last_log >= VIDEO_UPLOAD_LOG_INTERVAL_BYTES:
uploaded_mb = bytes_written / 1024 / 1024
size_note = f" из {total_bytes / 1024 / 1024:.1f} МБ" if total_bytes else ""
video.progress_percent = min(99, round(bytes_written / total_bytes * 100)) if total_bytes else 0
video.progress_log = "\n".join(
[video.progress_log, upload_log_line("Загрузка", f"Получено {uploaded_mb:.1f} МБ{size_note}")]
)
session.commit()
bytes_at_last_log = bytes_written
if not bytes_written:
raise HTTPException(status_code=422, detail="Загруженный файл пуст.")
duration = uploaded_video_duration(target)
os.chmod(target, 0o644)
size_mb = bytes_written / 1024 / 1024
video.local_video_path = str(target)
video.duration_seconds = duration
video.progress_percent = 0
video.progress_stage = "Готов к обработке"
video.progress_log = "\n".join(
[
video.progress_log,
upload_log_line("Загрузка", f"Файл сохранен: {size_mb:.1f} МБ"),
upload_log_line("Подготовка", f"Длительность определена: {duration} сек. Ролик готов к обработке."),
]
)
session.commit()
return {
"id": video.id,
"title": video.title,
"sourceUrl": video.source_url,
"durationSeconds": video.duration_seconds,
"status": video.status,
}
except Exception:
if video_dir.is_relative_to(root):
shutil.rmtree(video_dir, ignore_errors=True)
session.delete(video)
session.commit()
raise
finally:
await file.close()
@router.get("/api/videos")
def list_videos(session: Session = Depends(get_session)) -> list[dict]:
videos = session.scalars(

View file

@ -0,0 +1,71 @@
import asyncio
import io
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch
from fastapi import HTTPException, UploadFile
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from app.config import Settings
from app.database import Base
from app.models import Video
from app.routes import upload_video, video_storage_payload
class VideoUploadRouteTest(unittest.TestCase):
def setUp(self):
self.temp_dir = TemporaryDirectory()
root = Path(self.temp_dir.name)
self.settings = Settings(storage_dir=str(root / "data"))
self.engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(self.engine)
def tearDown(self):
self.temp_dir.cleanup()
def test_upload_streams_supported_video_to_dedicated_video_path(self):
file = UploadFile(filename="briefing.mp4", file=io.BytesIO(b"video-bytes"))
with Session(self.engine) as session, patch("app.routes.uploaded_video_duration", return_value=123):
payload = asyncio.run(upload_video(file, session, self.settings))
video = session.get(Video, payload["id"])
target = self.settings.videos_path / str(payload["id"]) / "video.mp4"
self.assertEqual(target.read_bytes(), b"video-bytes")
self.assertEqual(video.local_video_path, str(target))
self.assertEqual(video.duration_seconds, 123)
self.assertTrue(video.external_id.startswith("upload:"))
self.assertIn("Длительность определена", video.progress_log)
def test_upload_rejects_unsupported_extension(self):
file = UploadFile(filename="notes.txt", file=io.BytesIO(b"text"))
with Session(self.engine) as session:
with self.assertRaises(HTTPException) as error:
asyncio.run(upload_video(file, session, self.settings))
self.assertEqual(error.exception.status_code, 422)
def test_upload_cleans_video_row_and_partial_file_when_probe_fails(self):
file = UploadFile(filename="broken.mp4", file=io.BytesIO(b"not-a-video"))
with Session(self.engine) as session, patch(
"app.routes.uploaded_video_duration",
side_effect=HTTPException(status_code=422, detail="Видео не распознано."),
):
with self.assertRaises(HTTPException):
asyncio.run(upload_video(file, session, self.settings))
self.assertEqual(session.query(Video).count(), 0)
self.assertEqual(list(self.settings.videos_path.glob("*")), [])
def test_storage_payload_reports_capacity_bytes(self):
payload = video_storage_payload(self.settings)
self.assertEqual(set(payload), {"totalBytes", "usedBytes", "freeBytes", "usedPercent", "freePercent"})
self.assertGreater(payload["totalBytes"], 0)
self.assertGreaterEqual(payload["usedPercent"], 0)
if __name__ == "__main__":
unittest.main()