RezinaLMS-BackEnd/docs/vimeo-video-upload-progress-admin-panel-integration.md
2026-10-19 17:59:34 +03:00

35 KiB
Raw Permalink Blame History

Vimeo Video Upload Progress — Admin Panel Integration Guide

This guide documents how to implement real-time video upload progress in the Rezina 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:


Table of contents

  1. Feature overview
  2. How real-time progress works
  3. Architecture & sequence
  4. Backend prerequisites
  5. Authentication & RBAC
  6. Progress model (three phases)
  7. API reference
  8. Why not proxy video through the API
  9. Dependencies & project setup
  10. TypeScript types
  11. API client layer
  12. TUS upload with progress
  13. End-to-end upload orchestrator
  14. React hook & UI components
  15. Cancellable uploads
  16. Storing video in content forms
  17. Preview & embed after upload
  18. Error handling
  19. Edge cases & resilience
  20. Testing checklist
  21. Integration checklist
  22. Quick reference

Feature overview

Video lessons in Rezina 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 Rezina API (POST /vimeo/uploads/tus)
Byte-level upload progress Browser → Vimeo (tus-js-client onProgress)
Transcode / processing status Rezina API polls Vimeo (GET /vimeo/videos/:id/status)
Store in lesson/practice Admin form saves video_url / intro_video_url

The Rezina 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

┌─────────────────┐     POST /vimeo/uploads/tus      ┌──────────────┐
│  Admin panel    │ ─────────────────────────────────► │ Rezina 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    │ ─────────────────────────────────► │ Rezina 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

sequenceDiagram
    participant UI as Admin panel UI
    participant API as Rezina 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:

POST /api/v1/team/login
Content-Type: application/json

{ "email": "...", "password": "..." }
Authorization: Bearer <access_token>
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

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

{
  "message": "Human-readable message",
  "data": { },
  "success": true,
  "status_code": 200
}

Errors:

{
  "message": "Validation failed",
  "error": "Detailed error string"
}

Step 1 — Create TUS upload slot

POST /api/v1/vimeo/uploads/tus
Authorization: Bearer <token>
Content-Type: application/json

Request body:

{
  "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:

{
  "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 Rezina API)

Performed by tus-js-client against upload_link. See TUS upload with progress.

No Authorization header to Rezina API during this step. Vimeo authenticates via the upload URL.


Step 3 — Poll transcode status

GET /api/v1/vimeo/videos/{video_id}/status
Authorization: Bearer <token>

Success — 200 OK:

{
  "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

GET /api/v1/vimeo/videos/{video_id}
Authorization: Bearer <token>

Use after transcode completes to read duration, thumbnail_url, embed_url for preview cards.


Optional — Get embed HTML for preview

GET /api/v1/vimeo/videos/{video_id}/embed?width=640&height=360
Authorization: Bearer <token>

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

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()).

// Optional lazy load to reduce initial bundle
const tus = await import("tus-js-client");

Environment (admin panel)

VITE_API_BASE_URL=https://api.rezina.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:

export interface ApiResponse<T> {
  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:

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<never> {
  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<VimeoTusSlot> {
  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<VimeoTusSlot>;
  return json.data;
}

export async function getVimeoTranscodeStatus(
  token: string,
  videoId: string,
  signal?: AbortSignal
): Promise<VimeoTranscodeStatus> {
  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<VimeoTranscodeStatus>;
  return json.data;
}

TUS upload with progress

Create src/lib/video-upload/tus-upload.ts:

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<void>;
}

/**
 * Upload a File to Vimeo's upload_link with real-time progress.
 */
export function uploadFileViaTus(
  file: File,
  uploadLink: string,
  onProgress: (p: Pick<VideoUploadProgress, "bytesUploaded" | "bytesTotal" | "percent" | "message">) => void,
  signal?: AbortSignal
): TusUploadController {
  let upload: tus.Upload | null = null;

  const done = new Promise<void>((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:

PATCH <upload_link>
Tus-Resumable: 1.0.0
Upload-Offset: <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:

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<void> {
  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<VimeoVideoResult> {
  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

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<VideoUploadProgress>(idleProgress);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<VimeoVideoResult | null>(null);
  const abortRef = useRef<AbortController | null>(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

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 (
    <div className="video-upload-progress" role="status" aria-live="polite">
      <div className="progress-track">
        <div
          className="progress-fill"
          style={{ width: `${progress.percent}%` }}
        />
      </div>
      <div className="progress-meta">
        <span>{progress.message}</span>
        <span>{progress.percent}%</span>
      </div>
      {progress.phase === "uploading" &&
        progress.bytesTotal != null &&
        progress.bytesUploaded != null && (
          <span className="progress-bytes">
            {(progress.bytesUploaded / 1024 / 1024).toFixed(1)} MB /{" "}
            {(progress.bytesTotal / 1024 / 1024).toFixed(1)} MB
          </span>
        )}
      {showCancel && onCancel && (
        <button type="button" onClick={onCancel}>
          Cancel upload
        </button>
      )}
    </div>
  );
}

Video upload field (form integration)

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 (
    <div>
      <input
        type="file"
        accept="video/*,.mp4,.mov,.webm"
        disabled={disabled || isBusy}
        onChange={async (e) => {
          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 = "";
          }
        }}
      />

      <VideoUploadProgressBar progress={progress} onCancel={cancel} />

      {error && <p role="alert">{error}</p>}

      {value?.embedUrl && progress.phase === "done" && (
        <div className="video-preview">
          <iframe
            src={value.embedUrl}
            width={640}
            height={360}
            allow="autoplay; fullscreen; picture-in-picture"
            allowFullScreen
            title="Uploaded video preview"
          />
          <button type="button" onClick={() => { reset(); onChange(null); }}>
            Remove video
          </button>
        </div>
      )}
    </div>
  );
}

Form save guard

const formDisabled = isVideoUploadBusy || isSubmitting;

<button type="submit" disabled={formDisabled}>
  Save lesson
</button>

Block navigation during upload (optional):

useEffect(() => {
  if (!isBusy) return;
  const handler = (e: BeforeUnloadEvent) => {
    e.preventDefault();
    e.returnValue = "";
  };
  window.addEventListener("beforeunload", handler);
  return () => window.removeEventListener("beforeunload", handler);
}, [isBusy]);

Cancellable uploads

Action Implementation
User clicks Cancel tus.Upload.abort(true) via AbortController
Component unmount Call cancel() in useEffect cleanup
New file selected while uploading Abort previous upload before starting new one

Cancelled uploads do not delete the partial Vimeo video slot automatically. Orphan Vimeo entries can be cleaned up via DELETE /api/v1/vimeo/videos/:video_id (requires vimeo.videos.delete) if you track vimeo_id before cancel.


Storing video in content forms

After upload completes, persist stable Vimeo identifiers — not expiring URLs.

Fields by content type

Content API Field Value to store
LMS lesson video_url https://player.vimeo.com/video/{vimeo_id}
Exam prep lesson video_url Same player embed URL
Question set / practice intro_video_url Same player embed URL

Example lesson save payload:

{
  "title": "Introduction",
  "video_url": "https://player.vimeo.com/video/123456789",
  "thumbnail": "minio://image/abc.png"
}

You may also keep vimeo_id in local form state for admin preview/re-upload flows even if the public API only stores video_url.

When to save relative to upload

Strategy Recommendation
Save form only after upload + transcode complete Recommended for best UX
Save video_url immediately after TUS, poll transcode in background OK for long transcodes
Save on form submit while still processing Show "processing" badge on learner side

Preview & embed after upload

Quick preview (no extra API call)

<iframe src="https://player.vimeo.com/video/{vimeo_id}" ... />

Rich preview (duration, thumbnail)

GET /api/v1/vimeo/videos/{vimeo_id}

Response data includes thumbnail_url, duration, transcode_status.

Server-generated iframe HTML

GET /api/v1/vimeo/videos/{vimeo_id}/embed?width=640&height=360

Error handling

Scenario HTTP / signal UI action
Expired token 401 Redirect to login
Missing vimeo.uploads.tus 403 "Contact admin for video upload permission"
Vimeo not configured 503 Disable video upload feature
Invalid file_size 400 Validate file.size > 0 client-side
Video sent to presign 400 Route to Vimeo flow (should not happen)
TUS network error tus-js-client retries Show "Retrying…" (library handles)
TUS hard failure onError Show error + Retry button (new slot)
User cancel AbortError Reset UI, allow re-select
Transcode error status poll "Processing failed" + re-upload
Transcode timeout max poll attempts Allow save with warning or retry status check
Tab closed mid-upload beforeunload Warn user; upload may resume if same upload_link (advanced)

Always display API message and error when present:

const body = await res.json().catch(() => ({}));
throw new Error(body.error || body.message || `HTTP ${res.status}`);

Edge cases & resilience

Resumable uploads (tab refresh)

TUS supports resumption if you persist upload_link and use tus.Upload with findPreviousUploads / resumeFromPreviousUpload. This is optional for v1; implement if admins frequently lose connection on large files.

Duplicate slot on retry

Each POST /vimeo/uploads/tus creates a new Vimeo video. On retry after failure, create a new slot — do not reuse an old upload_link from a failed session.

Create the TUS slot immediately before upload. Do not cache upload_link for hours.

Concurrent uploads

Limit to one active video upload per form to avoid confusing progress state. Queue additional files if needed.

Throttle progress UI updates

onProgress can fire very frequently. Throttle React state updates if you see jank:

let last = 0;
onProgress: (bytesUploaded, bytesTotal) => {
  const now = Date.now();
  if (now - last < 200) return;
  last = now;
  // setState...
};

Slow 3G testing

Chrome DevTools → Network → Throttling. Verify progress bar moves smoothly during phase 2.


Testing checklist

Happy path

  • Select 50 MB MP4 → progress 0→100% → preview iframe plays
  • Save lesson with video_url → learner API returns correct embed URL
  • Progress shows MB transferred during upload phase

Permissions

  • User without vimeo.uploads.tus gets 403 on slot creation
  • INSTRUCTOR role can upload (if seeded)

Validation

  • Non-video file rejected client-side before API
  • Empty file rejected
  • POST /files/presign-upload with video returns 400 (if tested)

Errors & cancel

  • Cancel during upload stops TUS and resets UI
  • Airplane mode mid-upload → retry or error message
  • Transcode error shows re-upload option

UX

  • Form submit disabled while creating / uploading / processing
  • beforeunload warns when leaving mid-upload
  • Error messages show API error field

Performance

  • 500 MB+ file on throttled network — progress updates without freezing UI

Integration checklist

Backend / ops (verify once)

  • VIMEO_ACCESS_TOKEN set on API server
  • POST /vimeo/uploads/tus returns 201 in staging
  • Admin roles have vimeo.uploads.tus and vimeo.videos.status

Admin panel code

  • Install tus-js-client
  • Implement uploadVideoWithProgress orchestrator
  • Add useVideoUpload hook
  • Add VideoUploadField to lesson / practice / exam-prep forms
  • Store https://player.vimeo.com/video/{vimeo_id} in video_url / intro_video_url
  • Disable form save during active upload
  • Cancel button wired to tus.Upload.abort
  • Remove any video path using POST /files/upload

QA


Quick reference

Step Method Path Auth / permission
1. Create slot POST /api/v1/vimeo/uploads/tus Bearer + vimeo.uploads.tus
2. Upload bytes TUS PATCH {upload_link} from step 1 Vimeo upload URL (no Rezina token)
3. Poll transcode GET /api/v1/vimeo/videos/:video_id/status Bearer + vimeo.videos.status
Preview embed GET /api/v1/vimeo/videos/:video_id/embed Bearer + vimeo.videos.embed
Delete orphan DELETE /api/v1/vimeo/videos/:video_id Bearer + vimeo.videos.delete

Progress formula cheat sheet

creating:   percent = 2–5
uploading:  percent = 5 + (bytesUploaded / bytesTotal) * 75
processing: percent = min(99, 82 + pollAttempt)
done:       percent = 100

Storage cheat sheet

video_url / intro_video_url = https://player.vimeo.com/video/{vimeo_id}
canonical page link         = https://vimeo.com/{vimeo_id}

Last updated for Rezina API production branch — Vimeo TUS handlers in internal/web_server/handlers/vimeo.go.