diff --git a/src/components/video-upload/VideoUploadProgressBar.tsx b/src/components/video-upload/VideoUploadProgressBar.tsx new file mode 100644 index 0000000..304900c --- /dev/null +++ b/src/components/video-upload/VideoUploadProgressBar.tsx @@ -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 ( +
+
+
+
+
+ {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 ? ( + + ) : null} +
+ ) +} diff --git a/src/hooks/useVideoUpload.ts b/src/hooks/useVideoUpload.ts new file mode 100644 index 0000000..c1ffd23 --- /dev/null +++ b/src/hooks/useVideoUpload.ts @@ -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(idleProgress) + const [error, setError] = useState(null) + const [result, setResult] = useState(null) + const abortRef = useRef(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 } +} diff --git a/src/lib/video-upload/api.ts b/src/lib/video-upload/api.ts new file mode 100644 index 0000000..135f3fd --- /dev/null +++ b/src/lib/video-upload/api.ts @@ -0,0 +1,102 @@ +import http from "../../api/http" +import type { + ApiResponse, + CreateTusUploadRequest, + VimeoTranscodeStatus, + VimeoTusSlot, +} from "./types" + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value) +} + +function readString(raw: Record, ...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 { + const res = await http.post>("/vimeo/uploads/tus", body, { + signal, + }) + return normalizeVimeoTusSlot(res.data.data) +} + +export async function getVimeoTranscodeStatus( + videoId: string, + signal?: AbortSignal, +): Promise { + const res = await http.get>( + `/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 { + const res = await http.get>( + `/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 } +} diff --git a/src/lib/video-upload/tus-upload.ts b/src/lib/video-upload/tus-upload.ts new file mode 100644 index 0000000..3ebeb38 --- /dev/null +++ b/src/lib/video-upload/tus-upload.ts @@ -0,0 +1,61 @@ +import * as tus from "tus-js-client" +import type { VideoUploadProgress } from "./types" + +export interface TusUploadController { + abort: () => void + done: Promise +} + +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, + 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, + } +} diff --git a/src/lib/video-upload/types.ts b/src/lib/video-upload/types.ts new file mode 100644 index 0000000..25e5227 --- /dev/null +++ b/src/lib/video-upload/types.ts @@ -0,0 +1,74 @@ +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 +} + +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) +} diff --git a/src/lib/video-upload/upload-video.ts b/src/lib/video-upload/upload-video.ts new file mode 100644 index 0000000..be44d4d --- /dev/null +++ b/src/lib/video-upload/upload-video.ts @@ -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=` — taken from the page link + * (`https://vimeo.com//`) 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 { + 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 { + 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=). + 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, + } +} diff --git a/src/pages/content-management/AddNewLessonPage.tsx b/src/pages/content-management/AddNewLessonPage.tsx index 0e8264e..bd5f58e 100644 --- a/src/pages/content-management/AddNewLessonPage.tsx +++ b/src/pages/content-management/AddNewLessonPage.tsx @@ -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([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} />
{introVideoUrl.trim() ? ( @@ -436,6 +444,12 @@ export function AddNewLessonPage() { ) : null}
+ {introVideoProgress.phase !== "idle" ? ( + + ) : null} {introVideoPreview ? (

Preview

diff --git a/src/pages/content-management/AddNewPracticePage.tsx b/src/pages/content-management/AddNewPracticePage.tsx index f824b3c..5be90c3 100644 --- a/src/pages/content-management/AddNewPracticePage.tsx +++ b/src/pages/content-management/AddNewPracticePage.tsx @@ -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(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() { )} {uploadingIntroVideo - ? "Uploading…" + ? introVideoProgress.message || "Uploading…" : "Upload video from computer"}
+ {introVideoProgress.phase !== "idle" ? ( + + ) : null} {introVideoPreview ? (

diff --git a/src/pages/content-management/CourseModuleDetailPage.tsx b/src/pages/content-management/CourseModuleDetailPage.tsx index b88d79b..8019612 100644 --- a/src/pages/content-management/CourseModuleDetailPage.tsx +++ b/src/pages/content-management/CourseModuleDetailPage.tsx @@ -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(null); const createVideoFileInputRef = useRef(null); const [editingLessonId, setEditingLessonId] = useState(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(null); const editVideoFileInputRef = useRef(null); const [deletingLessonId, setDeletingLessonId] = useState(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() {

- {uploadingVideo ? "Uploading…" : "Click to upload"} + {uploadingVideo + ? createVideoProgress.message || "Uploading…" + : "Click to upload"} {" "} video from your computer @@ -698,6 +707,12 @@ export function CourseModuleDetailPage() {

+ {createVideoProgress.phase !== "idle" ? ( + + ) : null} setCreateVideoUrl(e.target.value)} @@ -963,7 +978,9 @@ export function CourseModuleDetailPage() {

- {uploadingEditVideo ? "Uploading…" : "Click to upload"} + {uploadingEditVideo + ? editVideoProgress.message || "Uploading…" + : "Click to upload"} {" "} video from your computer @@ -974,6 +991,12 @@ export function CourseModuleDetailPage() {

+ {editVideoProgress.phase !== "idle" ? ( + + ) : null} setEditVideoUrl(e.target.value)} diff --git a/src/pages/content-management/SpeakingPage.tsx b/src/pages/content-management/SpeakingPage.tsx index b427e6d..951c574 100644 --- a/src/pages/content-management/SpeakingPage.tsx +++ b/src/pages/content-management/SpeakingPage.tsx @@ -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(null) const [subCourseId, setSubCourseId] = useState("") const [subCourseOptions, setSubCourseOptions] = useState([]) @@ -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() { ) : ( )} - {uploadingIntroVideo ? "Uploading…" : "Upload video from computer"} + {uploadingIntroVideo + ? introVideoProgress.message || "Uploading…" + : "Upload video from computer"} {introVideoUrl.trim() ? ( ) : null} + {introVideoProgress.phase !== "idle" ? ( + + ) : null}

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

{introVideoPreview ? (
diff --git a/src/pages/content-management/SubCourseContentPage.tsx b/src/pages/content-management/SubCourseContentPage.tsx index 8f1a742..ae3e466 100644 --- a/src/pages/content-management/SubCourseContentPage.tsx +++ b/src/pages/content-management/SubCourseContentPage.tsx @@ -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("PUBLISHED") const [videoStatus, setVideoStatus] = useState("PUBLISHED") const [videoDisplayOrder, setVideoDisplayOrder] = useState(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/?h= - // where is the last path segment from `url` (e.g. https://vimeo.com//) - 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() {
+ {newVideoProgress.phase !== "idle" ? ( + + ) : null} {saveError &&

{saveError}

}
-
diff --git a/src/pages/content-management/components/LessonMediaUploadField.tsx b/src/pages/content-management/components/LessonMediaUploadField.tsx index 7b1a9d4..1242d24 100644 --- a/src/pages/content-management/components/LessonMediaUploadField.tsx +++ b/src/pages/content-management/components/LessonMediaUploadField.tsx @@ -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(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) => { @@ -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 (