Add real-time Vimeo TUS video upload progress across content forms.

Upload local videos directly to Vimeo with phase progress, cancel support, PascalCase API normalization, and privacy-hash player URLs.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-03 08:24:13 -07:00
parent 31cc7baa32
commit 4acde7ffc9
12 changed files with 793 additions and 118 deletions

View File

@ -0,0 +1,52 @@
import { Button } from "../ui/button"
import { cn } from "../../lib/utils"
import type { VideoUploadProgress } from "../../lib/video-upload/types"
interface VideoUploadProgressBarProps {
progress: VideoUploadProgress
onCancel?: () => void
className?: string
}
export function VideoUploadProgressBar({
progress,
onCancel,
className,
}: VideoUploadProgressBarProps) {
if (progress.phase === "idle") return null
const showCancel =
(progress.phase === "uploading" || progress.phase === "creating") && onCancel
return (
<div
className={cn("space-y-2 rounded-xl border border-grayScale-200 bg-grayScale-50/60 p-3", className)}
role="status"
aria-live="polite"
>
<div className="h-2 overflow-hidden rounded-full bg-grayScale-200">
<div
className="h-full rounded-full bg-[#9E2891] transition-[width] duration-200 ease-out"
style={{ width: `${Math.min(100, Math.max(0, progress.percent))}%` }}
/>
</div>
<div className="flex items-center justify-between gap-2 text-xs text-grayScale-600">
<span className="font-medium">{progress.message}</span>
<span className="tabular-nums text-grayScale-500">{progress.percent}%</span>
</div>
{progress.phase === "uploading" &&
progress.bytesTotal != null &&
progress.bytesUploaded != null && (
<p className="text-xs text-grayScale-500">
{(progress.bytesUploaded / 1024 / 1024).toFixed(1)} MB /{" "}
{(progress.bytesTotal / 1024 / 1024).toFixed(1)} MB
</p>
)}
{showCancel ? (
<Button type="button" variant="outline" size="sm" onClick={onCancel}>
Cancel upload
</Button>
) : null}
</div>
)
}

View File

@ -0,0 +1,77 @@
import { useCallback, useEffect, useRef, useState } from "react"
import { uploadVideoWithProgress } from "../lib/video-upload/upload-video"
import type { VideoUploadProgress, VimeoVideoResult } from "../lib/video-upload/types"
import { isVideoUploadBusy } from "../lib/video-upload/types"
const idleProgress: VideoUploadProgress = {
phase: "idle",
percent: 0,
message: "",
}
export function useVideoUpload() {
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 = isVideoUploadBusy(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(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
}
},
[],
)
const cancel = useCallback(() => {
abortRef.current?.abort()
abortRef.current = null
}, [])
const reset = useCallback(() => {
cancel()
setProgress(idleProgress)
setError(null)
setResult(null)
}, [cancel])
useEffect(() => {
if (!isBusy) return
const handler = (e: BeforeUnloadEvent) => {
e.preventDefault()
e.returnValue = ""
}
window.addEventListener("beforeunload", handler)
return () => window.removeEventListener("beforeunload", handler)
}, [isBusy])
useEffect(() => () => cancel(), [cancel])
return { upload, cancel, reset, progress, error, result, isBusy }
}

102
src/lib/video-upload/api.ts Normal file
View File

@ -0,0 +1,102 @@
import http from "../../api/http"
import type {
ApiResponse,
CreateTusUploadRequest,
VimeoTranscodeStatus,
VimeoTusSlot,
} from "./types"
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value)
}
function readString(raw: Record<string, unknown>, ...keys: string[]): string {
for (const key of keys) {
const value = raw[key]
if (value == null) continue
const text = String(value).trim()
if (text) return text
}
return ""
}
/** Backend may return PascalCase (Go json tags) or snake_case. */
function normalizeVimeoTusSlot(raw: unknown): VimeoTusSlot {
if (!isRecord(raw)) throw new Error("Invalid Vimeo TUS upload response")
const vimeo_id = readString(raw, "vimeo_id", "VimeoID", "VimeoId", "id", "ID")
const upload_link = readString(
raw,
"upload_link",
"UploadLink",
"UploadURL",
"upload_url",
)
const link = readString(raw, "link", "Link")
const uri = readString(raw, "uri", "URI", "Uri")
const status = readString(raw, "status", "Status") || "in_progress"
if (!vimeo_id) throw new Error("Vimeo TUS response missing video id")
if (!upload_link) throw new Error("Vimeo TUS response missing upload link")
return { vimeo_id, uri, link, upload_link, status }
}
function normalizeVimeoTranscodeStatus(raw: unknown): VimeoTranscodeStatus {
if (!isRecord(raw)) throw new Error("Invalid Vimeo transcode status response")
const video_id = readString(raw, "video_id", "VideoID", "VideoId", "vimeo_id", "VimeoID")
const status = readString(raw, "status", "Status", "transcode_status", "TranscodeStatus")
if (!video_id) throw new Error("Transcode status response missing video id")
if (!status) throw new Error("Transcode status response missing status")
return { video_id, status }
}
export async function createVimeoTusSlot(
body: CreateTusUploadRequest,
signal?: AbortSignal,
): Promise<VimeoTusSlot> {
const res = await http.post<ApiResponse<unknown>>("/vimeo/uploads/tus", body, {
signal,
})
return normalizeVimeoTusSlot(res.data.data)
}
export async function getVimeoTranscodeStatus(
videoId: string,
signal?: AbortSignal,
): Promise<VimeoTranscodeStatus> {
const res = await http.get<ApiResponse<unknown>>(
`/vimeo/videos/${encodeURIComponent(videoId.trim())}/status`,
{ signal },
)
return normalizeVimeoTranscodeStatus(res.data.data)
}
export interface VimeoVideoDetails {
vimeo_id: string
link: string
embed_url: string
}
/** Full video metadata (includes privacy-aware embed_url / link with hash). */
export async function getVimeoVideoDetails(
videoId: string,
signal?: AbortSignal,
): Promise<VimeoVideoDetails> {
const res = await http.get<ApiResponse<unknown>>(
`/vimeo/videos/${encodeURIComponent(videoId.trim())}`,
{ signal },
)
const raw = res.data.data
if (!isRecord(raw)) throw new Error("Invalid Vimeo video response")
const vimeo_id =
readString(raw, "vimeo_id", "VimeoID", "VimeoId", "id", "ID") || videoId.trim()
const link = readString(raw, "link", "Link")
const embed_url = readString(raw, "embed_url", "EmbedURL", "EmbedUrl")
return { vimeo_id, link, embed_url }
}

View File

@ -0,0 +1,61 @@
import * as tus from "tus-js-client"
import type { VideoUploadProgress } from "./types"
export interface TusUploadController {
abort: () => void
done: Promise<void>
}
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,
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,
}
}

View File

@ -0,0 +1,74 @@
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
}
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
onProgress?: (progress: VideoUploadProgress) => void
signal?: AbortSignal
transcodePollIntervalMs?: number
transcodeMaxAttempts?: number
}
export const VIDEO_UPLOAD_BUSY_PHASES: VideoUploadPhase[] = [
"creating",
"uploading",
"processing",
]
export function isVideoUploadBusy(phase: VideoUploadPhase): boolean {
return VIDEO_UPLOAD_BUSY_PHASES.includes(phase)
}

View File

@ -0,0 +1,213 @@
import { toVimeoEmbedUrl } from "../videoPreview"
import {
createVimeoTusSlot,
getVimeoTranscodeStatus,
getVimeoVideoDetails,
} from "./api"
import { uploadFileViaTus } from "./tus-upload"
import type { VideoUploadOptions, VideoUploadProgress, VimeoVideoResult } from "./types"
/**
* Build a playable player.vimeo.com URL.
* Private/unlisted videos require `?h=<privacy_hash>` — taken from the page link
* (`https://vimeo.com/<id>/<hash>`) or from API `embed_url`.
*/
function buildPlayerEmbedUrl(
vimeoId: string,
link?: string,
embedUrl?: string,
): string {
if (embedUrl?.trim()) {
const fromEmbed = toVimeoEmbedUrl(embedUrl.trim())
if (fromEmbed) return fromEmbed
if (embedUrl.includes("player.vimeo.com/video/")) return embedUrl.trim()
}
if (link?.trim()) {
const fromLink = toVimeoEmbedUrl(link.trim())
if (fromLink) return fromLink
}
return `https://player.vimeo.com/video/${vimeoId}`
}
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"))
})
})
}
export function validateVideoFile(file: File): void {
if (
!file.type.startsWith("video/") &&
!/\.(mp4|mov|webm|mkv|avi|m4v)$/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")
}
const twoGB = 2 * 1024 * 1024 * 1024
if (file.size > twoGB) {
throw new Error("Video exceeds 2 GB — check your Vimeo plan limits")
}
}
export function vimeoResultToStoredUrl(result: VimeoVideoResult): string {
return result.playerEmbedUrl
}
export async function uploadVideoWithProgress(
file: File,
options: VideoUploadOptions = {},
): Promise<VimeoVideoResult> {
const {
title,
description,
onProgress,
signal,
transcodePollIntervalMs = 5000,
transcodeMaxAttempts = 120,
} = options
validateVideoFile(file)
emit(onProgress, {
phase: "creating",
percent: 2,
message: "Creating Vimeo upload…",
})
const slot = await createVimeoTusSlot(
{
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,
})
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
}
emit(onProgress, {
phase: "processing",
percent: 82,
message: "Processing video on Vimeo…",
vimeoId: 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(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")
}
}
// Resolve privacy-aware embed URL (private/unlisted videos need ?h=<hash>).
let link = slot.link
let playerEmbedUrl = buildPlayerEmbedUrl(slot.vimeo_id, slot.link)
try {
const details = await getVimeoVideoDetails(slot.vimeo_id, signal)
if (details.link) link = details.link
playerEmbedUrl = buildPlayerEmbedUrl(
details.vimeo_id || slot.vimeo_id,
details.link || slot.link,
details.embed_url,
)
} catch {
// Fall back to slot link / bare player URL if metadata fetch fails.
}
emit(onProgress, {
phase: "done",
percent: 100,
message: "Video ready",
vimeoId: slot.vimeo_id,
})
return {
vimeoId: slot.vimeo_id,
link,
embedUrl: playerEmbedUrl,
playerEmbedUrl,
}
}

View File

@ -5,6 +5,9 @@ import { Link, useLocation, useNavigate, useParams } from "react-router-dom"
import { toast } from "sonner"
import { addQuestionToSet, createLesson, createQuestion } from "../../api/courses.api"
import { uploadVideoFile } from "../../api/files.api"
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar"
import { useVideoUpload } from "../../hooks/useVideoUpload"
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video"
import { PracticeQuestionEditorFields } from "../../components/content-management/PracticeQuestionEditorFields"
import type { PracticeQuestionDynamicRow } from "../../components/content-management/PracticeQuestionEditorFields"
import { buildDynamicQuestionPayload } from "../../lib/practiceDynamicQuestionPayload"
@ -140,7 +143,13 @@ export function AddNewLessonPage() {
const [lessonTitle, setLessonTitle] = useState("")
const [lessonDescription, setLessonDescription] = useState("")
const [introVideoUrl, setIntroVideoUrl] = useState("")
const [uploadingIntroVideo, setUploadingIntroVideo] = useState(false)
const {
upload: uploadIntroVideo,
cancel: cancelIntroVideo,
progress: introVideoProgress,
isBusy: uploadingIntroVideo,
} = useVideoUpload()
const [importingIntroVideoUrl, setImportingIntroVideoUrl] = useState(false)
const [questions, setQuestions] = useState<Question[]>([createEmptyQuestion("1")])
const handleNext = () => setCurrentStep((s) => (s < 3 ? ((s + 1) as Step) : s))
@ -150,21 +159,19 @@ export function AddNewLessonPage() {
const file = event.target.files?.[0]
event.target.value = ""
if (!file) return
setUploadingIntroVideo(true)
try {
const uploadRes = await uploadVideoFile(file, {
const res = await uploadIntroVideo(file, {
title: lessonTitle.trim() || file.name.replace(/\.[^.]+$/, "") || "Lesson intro",
description: lessonDescription.trim() || undefined,
})
const finalUrl = introVideoUrlFromUploadResponse(uploadRes.data?.data)
if (!finalUrl) throw new Error("Missing uploaded video url")
setIntroVideoUrl(finalUrl)
toast.success("Intro video uploaded")
if (res) {
setIntroVideoUrl(vimeoResultToStoredUrl(res))
toast.success("Intro video uploaded")
}
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") return
console.error("Failed to upload lesson intro video:", error)
notifyApiError(error, "Failed to upload intro video")
} finally {
setUploadingIntroVideo(false)
}
}
@ -182,7 +189,7 @@ export function AddNewLessonPage() {
}
// For non-direct URLs, automatically try server-side import via /files/upload.
setUploadingIntroVideo(true)
setImportingIntroVideoUrl(true)
try {
const uploadRes = await uploadVideoFile(source, {
title: lessonTitle.trim() || "Lesson intro",
@ -196,7 +203,7 @@ export function AddNewLessonPage() {
console.error("Failed to import intro video URL:", error)
notifyApiError(error, "Failed to import intro video URL")
} finally {
setUploadingIntroVideo(false)
setImportingIntroVideoUrl(false)
}
}
@ -417,17 +424,18 @@ export function AddNewLessonPage() {
inputMode="url"
autoComplete="off"
className="font-mono text-[13px]"
disabled={uploadingIntroVideo || importingIntroVideoUrl}
/>
<div className="flex flex-wrap items-center gap-2">
<label className="inline-flex cursor-pointer items-center gap-2 rounded-md border border-grayScale-200 px-3 py-2 text-xs text-grayScale-700 hover:bg-grayScale-50">
{uploadingIntroVideo ? <SpinnerIcon className="h-4 w-4" alt="" /> : <Upload className="h-4 w-4" />}
{uploadingIntroVideo ? "Uploading..." : "Upload video from computer"}
{uploadingIntroVideo ? introVideoProgress.message || "Uploading..." : "Upload video from computer"}
<input
type="file"
accept="video/*"
className="hidden"
onChange={handleIntroVideoFileChange}
disabled={uploadingIntroVideo}
disabled={uploadingIntroVideo || importingIntroVideoUrl}
/>
</label>
{introVideoUrl.trim() ? (
@ -436,6 +444,12 @@ export function AddNewLessonPage() {
</Button>
) : null}
</div>
{introVideoProgress.phase !== "idle" ? (
<VideoUploadProgressBar
progress={introVideoProgress}
onCancel={cancelIntroVideo}
/>
) : null}
{introVideoPreview ? (
<div className="rounded-xl border border-grayScale-200 bg-grayScale-50/40 p-3">
<p className="mb-2 text-xs font-medium text-grayScale-500">Preview</p>

View File

@ -28,6 +28,9 @@ import {
addQuestionToSet,
} from "../../api/courses.api";
import { uploadVideoFile } from "../../api/files.api";
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar";
import { useVideoUpload } from "../../hooks/useVideoUpload";
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video";
import type { QuestionOption } from "../../types/course.types";
import type { PracticeQuestionDynamicRow } from "../../components/content-management/PracticeQuestionEditorFields";
import { buildDynamicQuestionPayload } from "../../lib/practiceDynamicQuestionPayload";
@ -165,7 +168,12 @@ export function AddNewPracticePage() {
const [practiceTitle, setPracticeTitle] = useState("");
const [practiceDescription, setPracticeDescription] = useState("");
const [introVideoUrl, setIntroVideoUrl] = useState("");
const [uploadingIntroVideo, setUploadingIntroVideo] = useState(false);
const {
upload: uploadIntroVideo,
cancel: cancelIntroVideo,
progress: introVideoProgress,
isBusy: uploadingIntroVideo,
} = useVideoUpload();
const [importingIntroVideoUrl, setImportingIntroVideoUrl] = useState(false);
const introVideoFileInputRef = useRef<HTMLInputElement>(null);
const [shuffleQuestions, setShuffleQuestions] = useState(false);
@ -212,26 +220,24 @@ export function AddNewPracticePage() {
event.target.value = "";
if (!file) return;
setUploadingIntroVideo(true);
try {
const uploadRes = await uploadVideoFile(file, {
const res = await uploadIntroVideo(file, {
title:
practiceTitle.trim() ||
file.name.replace(/\.[^.]+$/, "") ||
"Practice intro",
description: practiceDescription.trim() || undefined,
});
const finalUrl = introVideoUrlFromUploadResponse(uploadRes.data?.data);
if (!finalUrl) throw new Error("Missing uploaded video url");
setIntroVideoUrl(finalUrl);
toast.success("Intro video uploaded", {
description: "The URL has been filled in for you.",
});
if (res) {
setIntroVideoUrl(vimeoResultToStoredUrl(res));
toast.success("Intro video uploaded", {
description: "The URL has been filled in for you.",
});
}
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") return;
console.error("Failed to upload intro video:", error);
notifyApiError(error, "Failed to upload intro video");
} finally {
setUploadingIntroVideo(false);
}
};
@ -607,7 +613,7 @@ export function AddNewPracticePage() {
<Upload className="h-4 w-4" />
)}
{uploadingIntroVideo
? "Uploading…"
? introVideoProgress.message || "Uploading…"
: "Upload video from computer"}
</Button>
<Button
@ -641,6 +647,12 @@ export function AddNewPracticePage() {
</Button>
) : null}
</div>
{introVideoProgress.phase !== "idle" ? (
<VideoUploadProgressBar
progress={introVideoProgress}
onCancel={cancelIntroVideo}
/>
) : null}
{introVideoPreview ? (
<div className="rounded-xl border border-grayScale-200 bg-grayScale-50/40 p-3">
<p className="mb-2 text-xs font-medium text-grayScale-500">

View File

@ -34,7 +34,10 @@ import {
setExamPrepModuleLessonPublishStatus,
setExamPrepUnitModulePublishStatus,
} from "../../api/courses.api";
import { uploadImageFile, uploadVideoFile } from "../../api/files.api";
import { uploadImageFile } from "../../api/files.api";
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar";
import { useVideoUpload } from "../../hooks/useVideoUpload";
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video";
import { resolveThumbnailForPreview } from "../../lib/videoPreview";
import type {
ContentAccessTier,
@ -124,7 +127,12 @@ export function CourseModuleDetailPage() {
const [createDescription, setCreateDescription] = useState("");
const [creatingLesson, setCreatingLesson] = useState(false);
const [uploadingThumbnail, setUploadingThumbnail] = useState(false);
const [uploadingVideo, setUploadingVideo] = useState(false);
const {
upload: uploadCreateVideo,
cancel: cancelCreateVideo,
progress: createVideoProgress,
isBusy: uploadingVideo,
} = useVideoUpload();
const createThumbnailFileInputRef = useRef<HTMLInputElement>(null);
const createVideoFileInputRef = useRef<HTMLInputElement>(null);
const [editingLessonId, setEditingLessonId] = useState<number | null>(null);
@ -135,7 +143,12 @@ export function CourseModuleDetailPage() {
const [editSortOrder, setEditSortOrder] = useState("1");
const [savingEdit, setSavingEdit] = useState(false);
const [uploadingEditThumbnail, setUploadingEditThumbnail] = useState(false);
const [uploadingEditVideo, setUploadingEditVideo] = useState(false);
const {
upload: uploadEditVideo,
cancel: cancelEditVideo,
progress: editVideoProgress,
isBusy: uploadingEditVideo,
} = useVideoUpload();
const editThumbnailFileInputRef = useRef<HTMLInputElement>(null);
const editVideoFileInputRef = useRef<HTMLInputElement>(null);
const [deletingLessonId, setDeletingLessonId] = useState<number | null>(null);
@ -270,22 +283,19 @@ export function CourseModuleDetailPage() {
toast.error("Please choose a video file");
return;
}
setUploadingVideo(true);
try {
const res = await uploadVideoFile(file, {
const res = await uploadCreateVideo(file, {
title: createTitle.trim() || "Lesson video",
description: createDescription.trim() || undefined,
});
const finalUrl =
res.data?.data?.url?.trim() || res.data?.data?.embed_url?.trim() || "";
if (!finalUrl) throw new Error("Upload did not return a video URL");
setCreateVideoUrl(finalUrl);
toast.success("Video uploaded");
if (res) {
setCreateVideoUrl(vimeoResultToStoredUrl(res));
toast.success("Video uploaded");
}
} catch (error: unknown) {
if (error instanceof DOMException && error.name === "AbortError") return;
console.error(error);
notifyApiError(error, "Failed to upload video");
} finally {
setUploadingVideo(false);
}
};
@ -403,22 +413,19 @@ export function CourseModuleDetailPage() {
toast.error("Please choose a video file");
return;
}
setUploadingEditVideo(true);
try {
const res = await uploadVideoFile(file, {
const res = await uploadEditVideo(file, {
title: editTitle.trim() || "Lesson video",
description: editDescription.trim() || undefined,
});
const finalUrl =
res.data?.data?.url?.trim() || res.data?.data?.embed_url?.trim() || "";
if (!finalUrl) throw new Error("Upload did not return a video URL");
setEditVideoUrl(finalUrl);
toast.success("Video uploaded");
if (res) {
setEditVideoUrl(vimeoResultToStoredUrl(res));
toast.success("Video uploaded");
}
} catch (error: unknown) {
if (error instanceof DOMException && error.name === "AbortError") return;
console.error(error);
notifyApiError(error, "Failed to upload video");
} finally {
setUploadingEditVideo(false);
}
};
@ -687,7 +694,9 @@ export function CourseModuleDetailPage() {
</div>
<p className="text-[15px]">
<span className="text-brand-500 font-bold hover:underline">
{uploadingVideo ? "Uploading…" : "Click to upload"}
{uploadingVideo
? createVideoProgress.message || "Uploading…"
: "Click to upload"}
</span>{" "}
<span className="text-grayScale-500">
video from your computer
@ -698,6 +707,12 @@ export function CourseModuleDetailPage() {
</p>
</div>
</button>
{createVideoProgress.phase !== "idle" ? (
<VideoUploadProgressBar
progress={createVideoProgress}
onCancel={cancelCreateVideo}
/>
) : null}
<Input
value={createVideoUrl}
onChange={(e) => setCreateVideoUrl(e.target.value)}
@ -963,7 +978,9 @@ export function CourseModuleDetailPage() {
</div>
<p className="text-[15px]">
<span className="text-brand-500 font-bold hover:underline">
{uploadingEditVideo ? "Uploading…" : "Click to upload"}
{uploadingEditVideo
? editVideoProgress.message || "Uploading…"
: "Click to upload"}
</span>{" "}
<span className="text-grayScale-500">
video from your computer
@ -974,6 +991,12 @@ export function CourseModuleDetailPage() {
</p>
</div>
</button>
{editVideoProgress.phase !== "idle" ? (
<VideoUploadProgressBar
progress={editVideoProgress}
onCancel={cancelEditVideo}
/>
) : null}
<Input
value={editVideoUrl}
onChange={(e) => setEditVideoUrl(e.target.value)}

View File

@ -21,7 +21,10 @@ import {
getQuestionSets,
updateQuestion,
} from "../../api/courses.api"
import { resolveFileUrl, uploadAudioFile, uploadImageFile, uploadVideoFile } from "../../api/files.api"
import { resolveFileUrl, uploadAudioFile, uploadImageFile } from "../../api/files.api"
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar"
import { useVideoUpload } from "../../hooks/useVideoUpload"
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video"
import { SpinnerIcon } from "../../components/ui/spinner-icon"
import {
DropdownMenu,
@ -115,18 +118,6 @@ function normalizeObjectKey(value: string) {
return trimmed
}
/** Prefer direct storage URL; for Vimeo pipeline match SubCourseContentPage player URL shape. */
function introVideoUrlFromUploadResponse(data: { url?: string; embed_url?: string } | undefined): string | null {
if (!data) return null
const pageUrl = data.url?.trim()
const embedUrl = data.embed_url?.trim()
if (embedUrl) {
const hashFromUrl = pageUrl ? pageUrl.split("/").filter(Boolean).at(-1) : undefined
return hashFromUrl ? `${embedUrl}?h=${hashFromUrl}` : embedUrl
}
return pageUrl || null
}
function toVimeoEmbedUrl(rawUrl: string): string | null {
try {
const parsed = new URL(rawUrl.trim())
@ -172,7 +163,12 @@ export function SpeakingPage() {
const [setTitle, setSetTitle] = useState("")
const [setDescription, setSetDescription] = useState("")
const [introVideoUrl, setIntroVideoUrl] = useState("")
const [uploadingIntroVideo, setUploadingIntroVideo] = useState(false)
const {
upload: uploadIntroVideo,
cancel: cancelIntroVideo,
progress: introVideoProgress,
isBusy: uploadingIntroVideo,
} = useVideoUpload()
const introVideoFileInputRef = useRef<HTMLInputElement>(null)
const [subCourseId, setSubCourseId] = useState("")
const [subCourseOptions, setSubCourseOptions] = useState<SubCourseOption[]>([])
@ -605,21 +601,19 @@ export function SpeakingPage() {
event.target.value = ""
if (!file) return
setUploadingIntroVideo(true)
try {
const uploadRes = await uploadVideoFile(file, {
const res = await uploadIntroVideo(file, {
title: setTitle.trim() || file.name.replace(/\.[^.]+$/, "") || "Speaking intro",
description: setDescription.trim() || undefined,
})
const finalUrl = introVideoUrlFromUploadResponse(uploadRes.data?.data)
if (!finalUrl) throw new Error("Missing uploaded video url")
setIntroVideoUrl(finalUrl)
toast.success("Intro video uploaded", { description: "The URL has been filled in for you." })
if (res) {
setIntroVideoUrl(vimeoResultToStoredUrl(res))
toast.success("Intro video uploaded", { description: "The URL has been filled in for you." })
}
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") return
console.error("Failed to upload intro video:", error)
notifyApiError(error, "Failed to upload intro video")
} finally {
setUploadingIntroVideo(false)
}
}
@ -1990,7 +1984,9 @@ export function SpeakingPage() {
) : (
<Upload className="h-4 w-4" />
)}
{uploadingIntroVideo ? "Uploading…" : "Upload video from computer"}
{uploadingIntroVideo
? introVideoProgress.message || "Uploading…"
: "Upload video from computer"}
</Button>
{introVideoUrl.trim() ? (
<Button type="button" variant="ghost" size="sm" onClick={() => setIntroVideoUrl("")}>
@ -1998,8 +1994,14 @@ export function SpeakingPage() {
</Button>
) : null}
</div>
{introVideoProgress.phase !== "idle" ? (
<VideoUploadProgressBar
progress={introVideoProgress}
onCancel={cancelIntroVideo}
/>
) : null}
<p className="text-xs leading-relaxed text-grayScale-500">
Paste a link or upload from your computer; uploads use the same file service as elsewhere. Optional, not tied to sub-course video rows.
Paste a Vimeo link or upload from your computer. Optional, not tied to sub-course video rows.
</p>
{introVideoPreview ? (
<div className="rounded-xl border border-grayScale-200 bg-black/95 p-2">

View File

@ -19,7 +19,9 @@ import {
getVimeoSample,
} from "../../api/courses.api"
import { getRatings } from "../../api/ratings.api"
import { uploadVideoFile } from "../../api/files.api"
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar"
import { useVideoUpload } from "../../hooks/useVideoUpload"
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video"
import type {
SubCourse,
QuestionSet,
@ -90,6 +92,12 @@ export function SubModuleContentPage() {
const [videoVisibility, setVideoVisibility] = useState<VideoVisibility>("PUBLISHED")
const [videoStatus, setVideoStatus] = useState<VideoStatus>("PUBLISHED")
const [videoDisplayOrder, setVideoDisplayOrder] = useState<number>(1)
const {
upload: uploadNewVideo,
cancel: cancelNewVideo,
progress: newVideoProgress,
isBusy: uploadingNewVideo,
} = useVideoUpload()
// Vimeo preview state
const [showPreviewModal, setShowPreviewModal] = useState(false)
@ -287,21 +295,16 @@ export function SubModuleContentPage() {
setSaving(true)
setSaveError(null)
try {
const uploadRes = await uploadVideoFile(videoFile, {
title: videoTitle.trim(),
description: videoDescription.trim(),
const uploadResult = await uploadNewVideo(videoFile, {
title: videoTitle.trim() || videoFile.name,
description: videoDescription.trim() || undefined,
})
if (!uploadResult) {
setSaving(false)
return
}
// Per backend guide, use embed_url as the video_url reference.
const embedUrl = uploadRes.data?.data?.embed_url?.trim()
const vimeoUrl = uploadRes.data?.data?.url?.trim()
if (!embedUrl) throw new Error("Missing uploaded video embed_url")
// Backend requires: https://player.vimeo.com/video/<id>?h=<hash>
// where <hash> is the last path segment from `url` (e.g. https://vimeo.com/<id>/<hash>)
const hashFromUrl = vimeoUrl ? vimeoUrl.split("/").filter(Boolean).at(-1) : undefined
const finalVideoUrl = hashFromUrl ? `${embedUrl}?h=${hashFromUrl}` : embedUrl
const finalVideoUrl = vimeoResultToStoredUrl(uploadResult)
const finalTitle = videoTitle.trim() || videoFile.name
await createCourseVideo({
@ -1108,18 +1111,30 @@ export function SubModuleContentPage() {
</select>
</div>
</div>
{newVideoProgress.phase !== "idle" ? (
<VideoUploadProgressBar
progress={newVideoProgress}
onCancel={cancelNewVideo}
/>
) : null}
{saveError && <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600">{saveError}</p>}
</div>
<div className="flex flex-col-reverse gap-2.5 border-t border-grayScale-100 px-6 py-4 sm:flex-row sm:justify-end sm:gap-3">
<Button variant="outline" onClick={() => setShowAddVideoModal(false)} disabled={saving}>
<Button
variant="outline"
onClick={() => setShowAddVideoModal(false)}
disabled={saving || uploadingNewVideo}
>
Cancel
</Button>
<Button
className="bg-brand-500 shadow-sm hover:bg-brand-600"
onClick={handleSaveNewVideo}
disabled={saving || !videoTitle.trim() || !videoFile}
disabled={saving || uploadingNewVideo || !videoTitle.trim() || !videoFile}
>
{saving ? "Uploading..." : "Upload Video"}
{saving || uploadingNewVideo
? newVideoProgress.message || "Uploading..."
: "Upload Video"}
</Button>
</div>
</div>

View File

@ -1,13 +1,15 @@
import { notifyApiError } from "../../../lib/apiErrors"
import { useCallback, useRef, useState, type ChangeEvent, type DragEvent } from "react";
import { useCallback, useEffect, useRef, useState, type ChangeEvent, type DragEvent } from "react";
import { CloudUpload } from "lucide-react";
import { toast } from "sonner";
import { Input } from "../../../components/ui/input";
import { cn } from "../../../lib/utils";
import { uploadImageFile, uploadVideoFile } from "../../../api/files.api";
import { uploadImageFile } from "../../../api/files.api";
import { useVideoUpload } from "../../../hooks/useVideoUpload";
import { VideoUploadProgressBar } from "../../../components/video-upload/VideoUploadProgressBar";
import { vimeoResultToStoredUrl } from "../../../lib/video-upload/upload-video";
const MAX_THUMB_BYTES = 5 * 1024 * 1024;
const MAX_VIDEO_BYTES = 2 * 1024 * 1024 * 1024;
const THUMB_TYPES = new Set(["image/jpeg", "image/png"]);
const VIDEO_TYPES_PREFIX = "video/";
@ -33,6 +35,9 @@ export interface LessonMediaUploadFieldProps {
disabled?: boolean;
onUploadBusyChange?: (busy: boolean) => void;
className?: string;
/** Vimeo title when uploading a video file */
videoTitle?: string;
videoDescription?: string;
}
export function LessonMediaUploadField({
@ -42,18 +47,22 @@ export function LessonMediaUploadField({
disabled = false,
onUploadBusyChange,
className,
videoTitle,
videoDescription,
}: LessonMediaUploadFieldProps) {
const fileInputRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
const [uploadingThumb, setUploadingThumb] = useState(false);
const [dragActive, setDragActive] = useState(false);
const { upload: uploadVideo, cancel: cancelVideo, progress: videoProgress, isBusy: videoBusy } =
useVideoUpload();
const setBusy = useCallback(
(next: boolean) => {
setUploading(next);
onUploadBusyChange?.(next);
},
[onUploadBusyChange],
);
const uploading = kind === "video" ? videoBusy : uploadingThumb;
useEffect(() => {
if (kind === "video") {
onUploadBusyChange?.(videoBusy);
}
}, [kind, videoBusy, onUploadBusyChange]);
const processFile = useCallback(
async (file: File) => {
@ -70,7 +79,8 @@ export function LessonMediaUploadField({
});
return;
}
setBusy(true);
setUploadingThumb(true);
onUploadBusyChange?.(true);
try {
const res = await uploadImageFile(file);
const url = res.data?.data?.url?.trim();
@ -81,7 +91,8 @@ export function LessonMediaUploadField({
console.error(e);
notifyApiError(e, "Failed to upload thumbnail");
} finally {
setBusy(false);
setUploadingThumb(false);
onUploadBusyChange?.(false);
}
return;
}
@ -90,27 +101,32 @@ export function LessonMediaUploadField({
toast.error("Please use a video file (e.g. MP4, WebM, MOV).");
return;
}
if (file.size > MAX_VIDEO_BYTES) {
toast.error("Video is too large", {
description: "Maximum size is 2 GB.",
});
return;
}
setBusy(true);
try {
const res = await uploadVideoFile(file);
const url = res.data?.data?.url?.trim();
if (!url) throw new Error("Upload did not return a file URL");
onChange(url);
toast.success("Video uploaded");
const res = await uploadVideo(file, {
title: videoTitle?.trim() || file.name,
description: videoDescription?.trim() || undefined,
});
if (res) {
onChange(vimeoResultToStoredUrl(res));
toast.success("Video uploaded");
}
} catch (e: unknown) {
if (e instanceof DOMException && e.name === "AbortError") return;
console.error(e);
notifyApiError(e, "Failed to upload video");
} finally {
setBusy(false);
}
},
[disabled, uploading, kind, onChange, setBusy],
[
disabled,
uploading,
kind,
onChange,
onUploadBusyChange,
uploadVideo,
videoTitle,
videoDescription,
],
);
const handleFileInputChange = (e: ChangeEvent<HTMLInputElement>) => {
@ -147,6 +163,15 @@ export function LessonMediaUploadField({
? "JPG, PNG (MAX 5 MB)"
: "MP4, MOV, WebM (MAX 2 GB)";
const videoUploadingLabel =
videoProgress.phase === "processing"
? videoProgress.message
: videoProgress.phase === "uploading"
? videoProgress.message
: videoProgress.phase === "creating"
? "Preparing upload…"
: "Uploading…";
return (
<div className={cn("space-y-3", className)}>
<label className="text-sm font-medium text-grayScale-700">
@ -178,8 +203,10 @@ export function LessonMediaUploadField({
zoneDisabled && "cursor-not-allowed opacity-60",
)}
>
{uploading ? (
{uploading && isThumb ? (
<p className="text-sm font-medium text-grayScale-600">Uploading…</p>
) : uploading && !isThumb ? (
<p className="text-sm font-medium text-grayScale-600">{videoUploadingLabel}</p>
) : (
<>
<CloudUpload
@ -197,6 +224,9 @@ export function LessonMediaUploadField({
</>
)}
</button>
{!isThumb && videoProgress.phase !== "idle" ? (
<VideoUploadProgressBar progress={videoProgress} onCancel={cancelVideo} />
) : null}
<Input
value={value}
onChange={(e) => onChange(e.target.value)}