dzen.nstarikov.ru/docs/superpowers/plans/2026-08-15-local-video-upload.md
nstarikov f3a557cf17
Some checks failed
Deploy Dzen assistant / deploy (push) Failing after 22s
chore: make dzen assistant repository root
2026-08-15 14:21:59 +03:00

9.5 KiB
Raw Blame History

Local Video Upload Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use subagent-driven development to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Let an authenticated administrator upload local video files to the Dzen Assistant, process them through the existing Whisper and Timeweb pipeline, track every stage, and store files exclusively on the dedicated 100 GB disk.

Architecture: API streams an uploaded file into the already-mounted /app/data/videos/{video_id} directory and creates the existing Video record. The current worker sees local_video_path, skips yt-dlp and continues from transcription. React uses XMLHttpRequest for byte-level upload progress, then switches the same card to its existing API/WebSocket processing log. A small capacity endpoint reads filesystem statistics for videos_path.

Tech Stack: FastAPI, Python multipart upload, ffprobe, SQLAlchemy/SQLite, Celery/Redis, React 19, TypeScript, Tailwind, Lucide, pytest, Docker Compose bind mounts.


Task 1: Test and implement storage helpers

Files:

  • Modify: app/config.py

  • Create: tests/test_video_storage.py

  • Step 1: Write failing tests for allowed local video extensions and disk capacity payload.

from pathlib import Path

from app.config import Settings


def test_video_storage_path_is_the_dedicated_videos_mount(tmp_path: Path):
    settings = Settings(storage_dir=str(tmp_path / "data"), video_storage_dir=str(tmp_path / "disk" / "videos"))
    assert settings.videos_path == tmp_path / "disk" / "videos"
  • Step 2: Run the focused test and confirm it fails because video_storage_dir does not exist.

Run: python -m unittest tests.test_video_storage -v

  • Step 3: Add video_storage_dir to Settings and make videos_path resolve it.
video_storage_dir: str = "/app/data/videos"

@property
def videos_path(self) -> Path:
    return Path(self.video_storage_dir)
  • Step 4: Run python -m unittest tests.test_video_storage -v and commit the focused configuration change.

Task 2: Implement uploaded-video API and capacity endpoint

Files:

  • Modify: app/routes.py

  • Create: tests/test_video_upload_routes.py

  • Step 1: Add failing route tests with a temporary Settings fixture.

def test_upload_rejects_unsupported_extension(client):
    response = client.post("/api/videos/upload", files={"file": ("notes.txt", b"text", "text/plain")})
    assert response.status_code == 422

def test_storage_endpoint_returns_byte_counts(client):
    response = client.get("/api/storage/videos")
    assert response.status_code == 200
    assert {"totalBytes", "usedBytes", "freeBytes", "usedPercent"} <= response.json().keys()
  • Step 2: Run python -m unittest tests.test_video_upload_routes -v; expect missing route failures.

  • Step 3: Add upload constants, safe extension validation and an ffprobe helper.

ALLOWED_VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov", ".mkv"}
MAX_UPLOAD_BYTES = 10 * 1024 * 1024 * 1024

def uploaded_video_duration(path: Path) -> int | None:
    result = subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", str(path)],
        capture_output=True, text=True, timeout=30, check=False,
    )
    return round(float(result.stdout.strip())) if result.returncode == 0 and result.stdout.strip() else None
  • Step 4: Add POST /api/videos/upload.

The route must create the Video row first with external_id="upload:{uuid4().hex}", source_url="upload://{id}", published_at=datetime.now(timezone.utc), status="new" and a start log. Stream the upload in 1 MiB chunks into settings.videos_path / str(video.id) / "video{suffix}"; update no more than once per 5 MiB in progress_log, enforce the 10 GiB limit and current shutil.disk_usage(settings.videos_path).free. On success run ffprobe, set local_video_path, duration, progress_percent=0, progress_stage="Готов к обработке", title from the basename and a completion log. On every failure remove only the created video directory and roll back the new row.

  • Step 5: Add GET /api/storage/videos.
usage = shutil.disk_usage(settings.videos_path)
return {
    "totalBytes": usage.total,
    "usedBytes": usage.used,
    "freeBytes": usage.free,
    "usedPercent": round(usage.used / usage.total * 100) if usage.total else 0,
}
  • Step 6: Run the route tests, python -m compileall app, and commit.

Task 3: Complete worker and deletion semantics for uploaded files

Files:

  • Modify: app/worker.py

  • Modify: app/routes.py

  • Create: tests/test_local_video_lifecycle.py

  • Step 1: Write failing tests for local-file processing and safe deletion.

def test_download_video_reuses_uploaded_file(video, tmp_path):
    uploaded = tmp_path / "12" / "video.mp4"
    uploaded.parent.mkdir()
    uploaded.write_bytes(b"video")
    video.local_video_path = str(uploaded)
    assert download_video(video) == uploaded

def test_delete_uploaded_video_removes_only_its_directory(client, uploaded_video):
    response = client.delete(f"/api/videos/{uploaded_video.id}")
    assert response.status_code == 200
    assert not Path(uploaded_video.local_video_path).parent.exists()
  • Step 2: Run python -m unittest tests.test_local_video_lifecycle -v; expect the delete-file assertion to fail.

  • Step 3: Update download_video log text to distinguish a manually uploaded local file from an already-downloaded VK file.

append_progress(video.id, 35, "Подготовка", "Использую загруженный видеофайл")
  • Step 4: Update DELETE /api/videos/{video_id} to remove settings.videos_path / str(video.id) only after resolving it and verifying it is a child of settings.videos_path.
video_dir = (settings.videos_path / str(video.id)).resolve()
root = settings.videos_path.resolve()
if video_dir.is_relative_to(root):
    shutil.rmtree(video_dir, ignore_errors=True)
  • Step 5: Run lifecycle tests and commit.

Task 4: Build the upload and disk UI

Files:

  • Modify: admin/src/App.tsx

  • Modify: admin/src/index.css only if a reusable drop-zone style is needed

  • Step 1: Define TypeScript contracts and state.

type VideoStorage = {
  totalBytes: number
  usedBytes: number
  freeBytes: number
  usedPercent: number
}

type UploadProgress = {
  name: string
  loaded: number
  total: number
}
  • Step 2: Add an XMLHttpRequest upload helper.
function uploadVideoFile(file: File) {
  return new Promise<Video>((resolve, reject) => {
    const request = new XMLHttpRequest()
    request.upload.onprogress = (event) => {
      if (event.lengthComputable) setUploadProgress({ name: file.name, loaded: event.loaded, total: event.total })
    }
    request.open("POST", "/api/videos/upload")
    request.withCredentials = true
    request.onload = () => request.status >= 200 && request.status < 300 ? resolve(JSON.parse(request.responseText)) : reject(new Error(request.responseText))
    request.onerror = () => reject(new Error("Не удалось загрузить видео."))
    const data = new FormData(); data.append("file", file); request.send(data)
  })
}
  • Step 3: Add a compact drop zone above the left list.

It accepts click-to-select and drag-and-drop, uses the Upload Lucide icon, presents the file name and exact MB count during transfer, disables duplicate submissions and uses existing toast notifications. It is responsive: input and progress stack on mobile.

  • Step 4: Add the dedicated-disk progress indicator beside the upload zone.

It loads /api/storage/videos on dashboard entry and after successful upload/delete. Render Видео на диске, a percentage bar and свободно X из Y; use amber only below 10 GiB free.

  • Step 5: Ensure success refreshes video data and opens no modal.

The uploaded video should appear first because the API already sorts manual videos by published_at at creation time.

  • Step 6: Run npm run build and commit.

Task 5: Integrate and validate in Docker production

Files:

  • Modify: .env.example if present, otherwise none

  • Modify: docker-compose.yml only if VIDEO_STORAGE_DIR=/app/data/videos needs explicit documentation

  • Step 1: Verify mount isolation.

Run: docker inspect dzen-assistant-api --format '{{range .Mounts}}{{println .Source .Destination}}{{end}}'

Expected: /var/www/dzen.nstarikov.ru/storage/videos /app/data/videos alongside the ordinary ./data /app/data mount.

  • Step 2: Build and recreate API and worker.

Run: docker compose build api worker && docker compose up -d --no-build api worker

Expected: both containers are Up and https://dzen.nstarikov.ru/health returns {"status":"ok"}.

  • Step 3: Perform the live acceptance path.

Upload a small MP4 through the admin: confirm megabyte progress, inspect its storage/videos/{id} file, run processing and confirm log sequence starts with the uploaded-file message. Delete it and verify only that directory disappears while another video directory remains.

  • Step 4: Run full verification and commit/push.

Run: python -m unittest discover -s tests -v && (cd admin && npm run build) && git diff --check

Commit only files from this feature, push main to Forgejo, and re-check production health plus /api/storage/videos while authenticated.