diff --git a/dzen-assistant/docs/superpowers/plans/2026-08-15-local-video-upload.md b/dzen-assistant/docs/superpowers/plans/2026-08-15-local-video-upload.md new file mode 100644 index 0000000..3101d5d --- /dev/null +++ b/dzen-assistant/docs/superpowers/plans/2026-08-15-local-video-upload.md @@ -0,0 +1,224 @@ +# 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.** + +```python +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.** + +```python +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.** + +```python +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.** + +```python +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`.** + +```python +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.** + +```python +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.** + +```python +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`.** + +```python +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.** + +```ts +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.** + +```ts +function uploadVideoFile(file: File) { + return new Promise