From 3ff43a3a22341bde219d5aaf6d6dc373690841df Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Tue, 7 Jul 2026 23:38:18 -0700 Subject: [PATCH] docs: add Vimeo video upload progress admin panel guide Document real-time TUS upload progress, transcode polling, and React integration patterns for the admin panel. Co-authored-by: Cursor --- docs/file-upload-admin-panel-integration.md | 2 + ...upload-progress-admin-panel-integration.md | 1264 +++++++++++++++++ 2 files changed, 1266 insertions(+) create mode 100644 docs/vimeo-video-upload-progress-admin-panel-integration.md diff --git a/docs/file-upload-admin-panel-integration.md b/docs/file-upload-admin-panel-integration.md index b5c1a917..b1597f72 100644 --- a/docs/file-upload-admin-panel-integration.md +++ b/docs/file-upload-admin-panel-integration.md @@ -421,6 +421,8 @@ If presign expires (15 min) before PUT completes, call `presign-upload` again wi ## Vimeo TUS upload (video) +> **Full guide:** [Vimeo Video Upload Progress — Admin Panel Integration](./vimeo-video-upload-progress-admin-panel-integration.md) — dedicated doc for real-time progress UI, React hooks, cancel/resume, and form integration. + Two main steps from the admin panel: **create TUS slot → upload via TUS client**. Optionally poll transcode status before enabling "Save" on the form. ### Step 1 — Create TUS upload slot diff --git a/docs/vimeo-video-upload-progress-admin-panel-integration.md b/docs/vimeo-video-upload-progress-admin-panel-integration.md new file mode 100644 index 00000000..d7e00d90 --- /dev/null +++ b/docs/vimeo-video-upload-progress-admin-panel-integration.md @@ -0,0 +1,1264 @@ +# Vimeo Video Upload Progress — Admin Panel Integration Guide + +This guide documents how to implement **real-time video upload progress** in the Yimaru admin panel when uploading videos to Vimeo. + +**Use this guide when:** admins pick a local video file (MP4, MOV, WebM, etc.) and need a live progress bar, cancel support, and post-upload transcode feedback before saving lesson or practice content. + +**Related guides:** + +- [File Upload — Admin Panel Integration](./file-upload-admin-panel-integration.md) — MinIO image/audio/PDF uploads and shared upload component patterns +- [Team Member Refresh Token](./team-member-refresh-token-admin-panel-integration.md) — obtaining and refreshing admin bearer tokens + +--- + +## Table of contents + +1. [Feature overview](#feature-overview) +2. [How real-time progress works](#how-real-time-progress-works) +3. [Architecture & sequence](#architecture--sequence) +4. [Backend prerequisites](#backend-prerequisites) +5. [Authentication & RBAC](#authentication--rbac) +6. [Progress model (three phases)](#progress-model-three-phases) +7. [API reference](#api-reference) +8. [Why not proxy video through the API](#why-not-proxy-video-through-the-api) +9. [Dependencies & project setup](#dependencies--project-setup) +10. [TypeScript types](#typescript-types) +11. [API client layer](#api-client-layer) +12. [TUS upload with progress](#tus-upload-with-progress) +13. [End-to-end upload orchestrator](#end-to-end-upload-orchestrator) +14. [React hook & UI components](#react-hook--ui-components) +15. [Cancellable uploads](#cancellable-uploads) +16. [Storing video in content forms](#storing-video-in-content-forms) +17. [Preview & embed after upload](#preview--embed-after-upload) +18. [Error handling](#error-handling) +19. [Edge cases & resilience](#edge-cases--resilience) +20. [Testing checklist](#testing-checklist) +21. [Integration checklist](#integration-checklist) +22. [Quick reference](#quick-reference) + +--- + +## Feature overview + +Video lessons in Yimaru are hosted on **Vimeo**. The admin panel uploads videos using **TUS 1.0.0** (resumable upload) directly from the browser to Vimeo's upload endpoint. + +| What | Where it happens | +|------|------------------| +| Create upload slot | Yimaru API (`POST /vimeo/uploads/tus`) | +| **Byte-level upload progress** | Browser → Vimeo (`tus-js-client` `onProgress`) | +| Transcode / processing status | Yimaru API polls Vimeo (`GET /vimeo/videos/:id/status`) | +| Store in lesson/practice | Admin form saves `video_url` / `intro_video_url` | + +The Yimaru API **never receives the video file bytes** during admin uploads. Real-time progress is therefore implemented **in the admin panel client**, not via WebSockets or server push from the backend. + +### User-visible phases + +| Phase | Label (example) | Progress source | +|-------|-------------------|-----------------| +| 1. Creating slot | "Preparing upload…" | Waiting for API | +| 2. Uploading | "Uploading… 47%" | TUS `onProgress` | +| 3. Processing | "Processing video…" | Poll transcode status | +| Done | "Video ready" | Transcode `complete` | + +--- + +## How real-time progress works + +```text +┌─────────────────┐ POST /vimeo/uploads/tus ┌──────────────┐ +│ Admin panel │ ─────────────────────────────────► │ Yimaru API │ +│ (browser) │ ◄──── upload_link + vimeo_id ───── │ │ +└────────┬────────┘ └──────────────┘ + │ + │ TUS PATCH chunks (5 MB default) + │ onProgress(bytesUploaded, bytesTotal) ◄── fires many times/sec + ▼ +┌─────────────────┐ +│ Vimeo TUS │ +│ upload endpoint │ +└─────────────────┘ + │ + │ after onSuccess + ▼ +┌─────────────────┐ GET /vimeo/videos/:id/status ┌──────────────┐ +│ Admin panel │ ─────────────────────────────────► │ Yimaru API │ +│ (poll loop) │ ◄──── { status: in_progress } ──── │ → Vimeo API │ +└─────────────────┘ └──────────────┘ +``` + +**Key insight:** `onProgress` fires as each chunk is uploaded. You map `(bytesUploaded / bytesTotal)` to your progress bar during phase 2. Phase 3 has no byte counter — use animated or time-based progress while polling. + +--- + +## Architecture & sequence + +```mermaid +sequenceDiagram + participant UI as Admin panel UI + participant API as Yimaru API + participant Vimeo as Vimeo TUS + transcode + + UI->>UI: User selects video file + UI->>UI: Validate size / MIME client-side + UI->>API: POST /vimeo/uploads/tus { name, file_size } + API->>Vimeo: Create TUS upload slot + API-->>UI: 201 { vimeo_id, upload_link, link } + + loop TUS chunks + UI->>Vimeo: PATCH upload_link (chunk) + Vimeo-->>UI: Upload-Offset updated + Note over UI: onProgress(bytesUploaded, bytesTotal) + end + + UI->>UI: TUS onSuccess + + loop Every 3–5s until complete or error + UI->>API: GET /vimeo/videos/:vimeo_id/status + API->>Vimeo: GET video transcode status + API-->>UI: { status: in_progress | complete | error } + Note over UI: Update processing progress + end + + UI->>UI: Store vimeo_id + player embed URL in form + UI->>API: PUT lesson / practice (separate save) +``` + +--- + +## Backend prerequisites + +The API server must have Vimeo configured. If not, upload endpoints return **503 Service Unavailable**. + +| Variable | Purpose | +|----------|---------| +| `VIMEO_ACCESS_TOKEN` | Vimeo API bearer token with upload scope | + +Relevant backend handlers (for reference): + +| Handler | Route | +|---------|-------| +| `CreateTusUpload` | `POST /api/v1/vimeo/uploads/tus` | +| `GetTranscodeStatus` | `GET /api/v1/vimeo/videos/:video_id/status` | +| `GetVimeoVideo` | `GET /api/v1/vimeo/videos/:video_id` | +| `GetEmbedCode` | `GET /api/v1/vimeo/videos/:video_id/embed` | + +**Do not use** `POST /api/v1/files/upload` or `POST /api/v1/files/presign-upload` for video. Presign returns **400** with guidance to use Vimeo TUS. + +--- + +## Authentication & RBAC + +### Token + +Use a **team member** access token on all calls: + +```http +POST /api/v1/team/login +Content-Type: application/json + +{ "email": "...", "password": "..." } +``` + +```http +Authorization: Bearer +Content-Type: application/json +``` + +Platform admin login (`POST /api/v1/auth/admin-login`) also works where your admin app already uses it. + +### Required permissions + +| Endpoint | RBAC permission | +|----------|-----------------| +| `POST /api/v1/vimeo/uploads/tus` | **`vimeo.uploads.tus`** | +| `GET /api/v1/vimeo/videos/:video_id/status` | **`vimeo.videos.status`** | +| `GET /api/v1/vimeo/videos/:video_id` | `vimeo.videos.get` | +| `GET /api/v1/vimeo/videos/:video_id/embed` | `vimeo.videos.embed` | + +Default seeded roles **`ADMIN`**, **`SUPER_ADMIN`**, and **`INSTRUCTOR`** include all `vimeo.*` permissions. Custom RBAC roles must be assigned `vimeo.uploads.tus` and `vimeo.videos.status` explicitly. + +`ADMIN` / `SUPER_ADMIN` bypass permission checks in middleware. + +### Troubleshooting 403 + +1. Confirm token is from team/admin login, not a learner (`STUDENT`) token. +2. In RBAC UI, verify role has `vimeo.uploads.tus`. +3. Re-login after permission changes. + +--- + +## Progress model (three phases) + +Use a single `UploadProgress` state object across all phases. + +### Phase weights + +| Phase | `phase` value | Percent range | Formula | +|-------|---------------|---------------|---------| +| Create slot | `creating` | 0–5% | Fixed at 2% until API returns | +| Upload bytes | `uploading` | 5–80% | `5 + (bytesUploaded / bytesTotal) * 75` | +| Transcode | `processing` | 80–99% | `min(99, 82 + pollAttempt)` or animated | +| Complete | `done` | 100% | — | +| Failed | `error` | — | Reset or keep last percent | + +### TypeScript progress type + +```typescript +export type VideoUploadPhase = + | "idle" + | "creating" + | "uploading" + | "processing" + | "done" + | "error" + | "cancelled"; + +export interface VideoUploadProgress { + phase: VideoUploadPhase; + /** 0–100 overall progress across all phases */ + percent: number; + /** Human-readable status line */ + message: string; + /** Raw byte progress during uploading phase (optional, for detail UI) */ + bytesUploaded?: number; + bytesTotal?: number; + /** Set after slot creation */ + vimeoId?: string; +} +``` + +### Transcode status mapping + +| Vimeo `status` | UI message | Action | +|----------------|------------|--------| +| `in_progress` | "Processing video on Vimeo…" | Keep polling | +| `complete` | "Video ready" | Enable form save, show preview | +| `error` | "Video processing failed" | Offer re-upload | +| `unknown` | "Checking status…" | Keep polling (short window) | + +Poll every **3–5 seconds**. Stop after **120 attempts** (~10 minutes at 5s) and show "Still processing — you can save and check back later" if upload succeeded but transcode is slow. + +--- + +## API reference + +Base path: `/api/v1` + +### Standard response envelope + +```json +{ + "message": "Human-readable message", + "data": { }, + "success": true, + "status_code": 200 +} +``` + +Errors: + +```json +{ + "message": "Validation failed", + "error": "Detailed error string" +} +``` + +--- + +### Step 1 — Create TUS upload slot + +```http +POST /api/v1/vimeo/uploads/tus +Authorization: Bearer +Content-Type: application/json +``` + +**Request body:** + +```json +{ + "name": "Unit 3 — Listening Introduction", + "description": "Optional lesson intro video", + "file_size": 52428800 +} +``` + +| Field | Required | Rules | +|-------|----------|-------| +| `name` | Yes | Video title in Vimeo | +| `description` | No | Optional | +| `file_size` | Yes | Must be `> 0` (bytes). Use `file.size` from the `File` object. | + +**Success — `201 Created`:** + +```json +{ + "message": "Vimeo TUS upload created successfully", + "data": { + "vimeo_id": "123456789", + "uri": "/videos/123456789", + "link": "https://vimeo.com/123456789", + "upload_link": "https://global.upload.vimeo.com/tus/uploads/xxxxx", + "status": "in_progress" + }, + "success": true, + "status_code": 201 +} +``` + +**Save immediately:** + +- `vimeo_id` — for status polling and storage +- `upload_link` — pass to `tus-js-client` (single-use for this session) + +**Common errors:** + +| HTTP | Cause | +|------|-------| +| 400 | Invalid body / validation | +| 401 | Missing or expired token | +| 403 | Missing `vimeo.uploads.tus` | +| 503 | Vimeo not configured on server | + +--- + +### Step 2 — Upload file (browser → Vimeo, not Yimaru API) + +Performed by `tus-js-client` against `upload_link`. See [TUS upload with progress](#tus-upload-with-progress). + +No `Authorization` header to Yimaru API during this step. Vimeo authenticates via the upload URL. + +--- + +### Step 3 — Poll transcode status + +```http +GET /api/v1/vimeo/videos/{video_id}/status +Authorization: Bearer +``` + +**Success — `200 OK`:** + +```json +{ + "message": "Transcode status retrieved successfully", + "data": { + "video_id": "123456789", + "status": "in_progress" + }, + "success": true, + "status_code": 200 +} +``` + +Poll until `status` is `complete` or `error`. + +--- + +### Optional — Get full video metadata + +```http +GET /api/v1/vimeo/videos/{video_id} +Authorization: Bearer +``` + +Use after transcode completes to read `duration`, `thumbnail_url`, `embed_url` for preview cards. + +--- + +### Optional — Get embed HTML for preview + +```http +GET /api/v1/vimeo/videos/{video_id}/embed?width=640&height=360 +Authorization: Bearer +``` + +Returns `embed_url` and `embed_html` for an iframe preview in the admin form. + +--- + +## Why not proxy video through the API + +| Approach | Real-time progress | Resumable | Server load | +|----------|-------------------|-----------|-------------| +| **TUS browser → Vimeo** (recommended) | Yes (`onProgress`) | Yes | Low | +| `POST /files/upload` multipart → API → Vimeo | No | No | High (500 MB cap) | +| Pull upload (`POST /vimeo/uploads/pull`) | No browser progress | N/A | Vimeo fetches URL | + +The backend's `UploadVideoFile` server-side TUS PATCH has no progress callback — it is for internal/server use only, not admin UI. + +--- + +## Dependencies & project setup + +### npm + +```bash +npm install tus-js-client +``` + +### Vite / bundler note + +`tus-js-client` works in modern browsers. If you use SSR, only import it in client components (`"use client"` in Next.js, or dynamic `import()`). + +```typescript +// Optional lazy load to reduce initial bundle +const tus = await import("tus-js-client"); +``` + +### Environment (admin panel) + +```env +VITE_API_BASE_URL=https://api.yimaru.com +``` + +### Network / CORS + +- Browser must reach `*.upload.vimeo.com` over HTTPS. +- No MinIO CORS configuration applies to Vimeo. +- Corporate firewalls blocking Vimeo upload hosts will break step 2. + +--- + +## TypeScript types + +Create `src/lib/video-upload/types.ts`: + +```typescript +export interface ApiResponse { + message: string; + data: T; + success?: boolean; + status_code?: number; +} + +export interface ApiErrorBody { + message: string; + error?: string; +} + +export interface CreateTusUploadRequest { + name: string; + description?: string; + file_size: number; +} + +export interface VimeoTusSlot { + vimeo_id: string; + uri: string; + link: string; + upload_link: string; + status: string; +} + +export interface VimeoTranscodeStatus { + video_id: string; + status: string; // in_progress | complete | error | unknown +} + +export interface VimeoVideoResult { + vimeoId: string; + link: string; + embedUrl: string; + playerEmbedUrl: string; +} + +export type VideoUploadPhase = + | "idle" + | "creating" + | "uploading" + | "processing" + | "done" + | "error" + | "cancelled"; + +export interface VideoUploadProgress { + phase: VideoUploadPhase; + percent: number; + message: string; + bytesUploaded?: number; + bytesTotal?: number; + vimeoId?: string; +} + +export interface VideoUploadOptions { + title?: string; + description?: string; + /** Called on every progress tick */ + onProgress?: (progress: VideoUploadProgress) => void; + /** AbortSignal to cancel from outside */ + signal?: AbortSignal; + /** Poll interval ms for transcode (default 5000) */ + transcodePollIntervalMs?: number; + /** Max poll attempts (default 120) */ + transcodeMaxAttempts?: number; +} +``` + +--- + +## API client layer + +Create `src/lib/video-upload/api.ts`: + +```typescript +import type { + ApiErrorBody, + ApiResponse, + CreateTusUploadRequest, + VimeoTranscodeStatus, + VimeoTusSlot, +} from "./types"; + +const API_BASE = import.meta.env.VITE_API_BASE_URL?.replace(/\/$/, "") ?? ""; + +function authHeaders(token: string): HeadersInit { + return { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + }; +} + +async function parseApiError(res: Response): Promise { + const body = (await res.json().catch(() => ({}))) as ApiErrorBody; + throw new Error(body.error || body.message || `HTTP ${res.status}`); +} + +export async function createVimeoTusSlot( + token: string, + body: CreateTusUploadRequest, + signal?: AbortSignal +): Promise { + const res = await fetch(`${API_BASE}/api/v1/vimeo/uploads/tus`, { + method: "POST", + headers: authHeaders(token), + body: JSON.stringify(body), + signal, + }); + if (!res.ok) await parseApiError(res); + const json = (await res.json()) as ApiResponse; + return json.data; +} + +export async function getVimeoTranscodeStatus( + token: string, + videoId: string, + signal?: AbortSignal +): Promise { + const res = await fetch(`${API_BASE}/api/v1/vimeo/videos/${videoId}/status`, { + headers: authHeaders(token), + signal, + }); + if (!res.ok) await parseApiError(res); + const json = (await res.json()) as ApiResponse; + return json.data; +} +``` + +--- + +## TUS upload with progress + +Create `src/lib/video-upload/tus-upload.ts`: + +```typescript +import * as tus from "tus-js-client"; +import type { VideoUploadProgress } from "./types"; + +export interface TusUploadController { + /** Abort in-flight upload */ + abort: () => void; + /** Promise resolves when upload completes */ + done: Promise; +} + +/** + * Upload a File to Vimeo's upload_link with real-time progress. + */ +export function uploadFileViaTus( + file: File, + uploadLink: string, + onProgress: (p: Pick) => void, + signal?: AbortSignal +): TusUploadController { + let upload: tus.Upload | null = null; + + const done = new Promise((resolve, reject) => { + upload = new tus.Upload(file, { + uploadUrl: uploadLink, + // 5 MB chunks — good balance for progress granularity vs request count + chunkSize: 5 * 1024 * 1024, + retryDelays: [0, 1000, 3000, 5000, 10000, 20000], + metadata: { + filename: file.name, + filetype: file.type || "video/mp4", + }, + onError: (error) => { + if (signal?.aborted) { + reject(new DOMException("Upload cancelled", "AbortError")); + return; + } + reject(error); + }, + onProgress: (bytesUploaded, bytesTotal) => { + const ratio = bytesTotal > 0 ? bytesUploaded / bytesTotal : 0; + const percent = Math.round(5 + ratio * 75); + onProgress({ + bytesUploaded, + bytesTotal, + percent, + message: `Uploading… ${Math.round(ratio * 100)}%`, + }); + }, + onSuccess: () => resolve(), + }); + + if (signal) { + signal.addEventListener("abort", () => { + upload?.abort(true); + }); + } + + upload.start(); + }); + + return { + abort: () => upload?.abort(true), + done, + }; +} +``` + +### TUS protocol details (reference) + +The backend's server-side implementation uses: + +```http +PATCH +Tus-Resumable: 1.0.0 +Upload-Offset: +Content-Type: application/offset+octet-stream +``` + +`tus-js-client` manages offsets, chunking, and retries automatically. **Always prefer the library** over hand-rolled PATCH requests. + +--- + +## End-to-end upload orchestrator + +Create `src/lib/video-upload/upload-video.ts`: + +```typescript +import { createVimeoTusSlot, getVimeoTranscodeStatus } from "./api"; +import { uploadFileViaTus } from "./tus-upload"; +import type { VideoUploadOptions, VideoUploadProgress, VimeoVideoResult } from "./types"; + +function emit( + onProgress: VideoUploadOptions["onProgress"], + progress: VideoUploadProgress +) { + onProgress?.(progress); +} + +function sleep(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new DOMException("Cancelled", "AbortError")); + return; + } + const t = setTimeout(resolve, ms); + signal?.addEventListener("abort", () => { + clearTimeout(t); + reject(new DOMException("Cancelled", "AbortError")); + }); + }); +} + +/** Client-side validation before any API call */ +export function validateVideoFile(file: File): void { + if (!file.type.startsWith("video/") && !/\.(mp4|mov|webm|mkv|avi)$/i.test(file.name)) { + throw new Error("Please select a video file (MP4, MOV, WebM, etc.)"); + } + if (file.size <= 0) { + throw new Error("File is empty"); + } + // Soft warning threshold — adjust to your Vimeo plan + const twoGB = 2 * 1024 * 1024 * 1024; + if (file.size > twoGB) { + throw new Error("Video exceeds 2 GB — check your Vimeo plan limits"); + } +} + +/** + * Full flow: create slot → TUS upload with progress → poll transcode. + */ +export async function uploadVideoWithProgress( + token: string, + file: File, + options: VideoUploadOptions = {} +): Promise { + const { + title, + description, + onProgress, + signal, + transcodePollIntervalMs = 5000, + transcodeMaxAttempts = 120, + } = options; + + validateVideoFile(file); + + // Phase 1: create slot + emit(onProgress, { + phase: "creating", + percent: 2, + message: "Creating Vimeo upload…", + }); + + const slot = await createVimeoTusSlot( + token, + { + name: title?.trim() || file.name, + description: description?.trim() || undefined, + file_size: file.size, + }, + signal + ); + + emit(onProgress, { + phase: "creating", + percent: 5, + message: "Upload starting…", + vimeoId: slot.vimeo_id, + }); + + // Phase 2: TUS upload (real-time byte progress) + const tusController = uploadFileViaTus( + file, + slot.upload_link, + ({ bytesUploaded, bytesTotal, percent, message }) => { + emit(onProgress, { + phase: "uploading", + percent, + message, + bytesUploaded, + bytesTotal, + vimeoId: slot.vimeo_id, + }); + }, + signal + ); + + try { + await tusController.done; + } catch (e) { + if (signal?.aborted) { + emit(onProgress, { phase: "cancelled", percent: 0, message: "Upload cancelled" }); + throw e; + } + emit(onProgress, { + phase: "error", + percent: 0, + message: e instanceof Error ? e.message : "Upload failed", + vimeoId: slot.vimeo_id, + }); + throw e; + } + + // Phase 3: transcode polling + emit(onProgress, { + phase: "processing", + percent: 82, + message: "Processing video on Vimeo…", + vimeoId: slot.vimeo_id, + }); + + const embedUrl = `https://player.vimeo.com/video/${slot.vimeo_id}`; + let status = "in_progress"; + let attempt = 0; + + while (status === "in_progress" || status === "unknown") { + if (attempt >= transcodeMaxAttempts) { + throw new Error( + "Video uploaded but processing is taking longer than expected. You may save the video ID and refresh later." + ); + } + await sleep(transcodePollIntervalMs, signal); + const res = await getVimeoTranscodeStatus(token, slot.vimeo_id, signal); + status = res.status; + attempt += 1; + + emit(onProgress, { + phase: "processing", + percent: Math.min(99, 82 + Math.floor(attempt / 2)), + message: + status === "in_progress" || status === "unknown" + ? "Processing video on Vimeo…" + : `Processing: ${status}`, + vimeoId: slot.vimeo_id, + }); + + if (status === "complete") break; + if (status === "error") { + emit(onProgress, { + phase: "error", + percent: 0, + message: "Vimeo failed to process this video", + vimeoId: slot.vimeo_id, + }); + throw new Error("Video processing failed on Vimeo"); + } + } + + emit(onProgress, { + phase: "done", + percent: 100, + message: "Video ready", + vimeoId: slot.vimeo_id, + }); + + return { + vimeoId: slot.vimeo_id, + link: slot.link, + embedUrl, + playerEmbedUrl: embedUrl, + }; +} +``` + +--- + +## React hook & UI components + +### Hook — `useVideoUpload.ts` + +```typescript +import { useCallback, useRef, useState } from "react"; +import { uploadVideoWithProgress } from "../lib/video-upload/upload-video"; +import type { VideoUploadProgress, VimeoVideoResult } from "../lib/video-upload/types"; + +const idleProgress: VideoUploadProgress = { + phase: "idle", + percent: 0, + message: "", +}; + +export function useVideoUpload(token: string) { + const [progress, setProgress] = useState(idleProgress); + const [error, setError] = useState(null); + const [result, setResult] = useState(null); + const abortRef = useRef(null); + + const isBusy = ["creating", "uploading", "processing"].includes(progress.phase); + + const upload = useCallback( + async (file: File, opts?: { title?: string; description?: string }) => { + abortRef.current?.abort(); + const ac = new AbortController(); + abortRef.current = ac; + + setError(null); + setResult(null); + setProgress({ phase: "creating", percent: 0, message: "Starting…" }); + + try { + const data = await uploadVideoWithProgress(token, file, { + ...opts, + signal: ac.signal, + onProgress: setProgress, + }); + setResult(data); + return data; + } catch (e) { + if (e instanceof DOMException && e.name === "AbortError") { + setProgress({ phase: "cancelled", percent: 0, message: "Cancelled" }); + return null; + } + const msg = e instanceof Error ? e.message : "Upload failed"; + setError(msg); + setProgress((p) => ({ ...p, phase: "error", message: msg })); + throw e; + } + }, + [token] + ); + + const cancel = useCallback(() => { + abortRef.current?.abort(); + abortRef.current = null; + }, []); + + const reset = useCallback(() => { + cancel(); + setProgress(idleProgress); + setError(null); + setResult(null); + }, [cancel]); + + return { upload, cancel, reset, progress, error, result, isBusy }; +} +``` + +### Progress bar component + +```tsx +import type { VideoUploadProgress } from "../lib/video-upload/types"; + +interface VideoUploadProgressBarProps { + progress: VideoUploadProgress; + onCancel?: () => void; +} + +export function VideoUploadProgressBar({ progress, onCancel }: VideoUploadProgressBarProps) { + if (progress.phase === "idle") return null; + + const showCancel = progress.phase === "uploading" || progress.phase === "creating"; + + return ( +
+
+
+
+
+ {progress.message} + {progress.percent}% +
+ {progress.phase === "uploading" && + progress.bytesTotal != null && + progress.bytesUploaded != null && ( + + {(progress.bytesUploaded / 1024 / 1024).toFixed(1)} MB /{" "} + {(progress.bytesTotal / 1024 / 1024).toFixed(1)} MB + + )} + {showCancel && onCancel && ( + + )} +
+ ); +} +``` + +### Video upload field (form integration) + +```tsx +import { useVideoUpload } from "../hooks/useVideoUpload"; +import { VideoUploadProgressBar } from "./VideoUploadProgressBar"; + +interface VideoUploadFieldProps { + token: string; + value?: { vimeoId: string; embedUrl: string } | null; + onChange: (value: { vimeoId: string; embedUrl: string; link: string } | null) => void; + disabled?: boolean; +} + +export function VideoUploadField({ token, value, onChange, disabled }: VideoUploadFieldProps) { + const { upload, cancel, progress, error, result, isBusy, reset } = useVideoUpload(token); + + return ( +
+ { + const file = e.target.files?.[0]; + if (!file) return; + try { + const res = await upload(file, { title: file.name }); + if (res) { + onChange({ + vimeoId: res.vimeoId, + embedUrl: res.embedUrl, + link: res.link, + }); + } + } catch { + /* error state handled in hook */ + } finally { + e.target.value = ""; + } + }} + /> + + + + {error &&

{error}

} + + {value?.embedUrl && progress.phase === "done" && ( +
+