Files
compor-academy/components/course/LessonVideo.tsx
Cauê Faleiros 21085e887d
All checks were successful
CI / Validate frontend and API (push) Successful in 2m22s
CI / Build and publish Docker images (push) Successful in 1m6s
feat: finalize academy redesign and production readiness
Align admin, community, search, library, learning and course management with the mockup. Add saved courses, download history, public community feed, instructor directory, backend search, course views, admin content tools and community moderation. Harden API and Nginx for production.
2026-11-05 15:06:53 -03:00

130 lines
4.9 KiB
TypeScript

import React, { useEffect, useRef, useState } from 'react';
import { CircleNotchIcon, WarningCircleIcon } from '@phosphor-icons/react';
import { Lesson } from '../../types';
import { courseApi, LessonPlayback } from '../../services/api';
declare global {
interface Window {
playerjs?: {
Player: new (element: HTMLIFrameElement) => {
on: (event: string, listener: (data?: { seconds?: number; duration?: number }) => void) => void;
};
};
}
}
let bunnyPlayerJsPromise: Promise<void> | null = null;
const loadBunnyPlayerJs = () => {
if (window.playerjs) return Promise.resolve();
if (bunnyPlayerJsPromise) return bunnyPlayerJsPromise;
bunnyPlayerJsPromise = new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'https://assets.mediadelivery.net/playerjs/player-0.1.0.min.js';
script.async = true;
script.onload = () => resolve();
script.onerror = () => reject(new Error('Bunny player events could not be loaded'));
document.head.appendChild(script);
});
return bunnyPlayerJsPromise;
};
interface LessonVideoProps {
courseId: string;
lesson: Lesson;
/** Saved position to resume from (HTML video only; Bunny resumes on its own). */
resumeAt: number;
/** Called on playback progress with the current second (and duration when known). */
onTime: (seconds: number, duration?: number) => void;
/** Called when the video finished playing. `autoAdvance` is true for HTML video, as before. */
onEnded: (seconds: number, autoAdvance: boolean) => void;
className?: string;
}
/**
* The API verifies the session before returning a time-limited Bunny embed URL;
* a video provider key is never sent to the browser.
*/
export const LessonVideo: React.FC<LessonVideoProps> = ({ courseId, lesson, resumeAt, onTime, onEnded, className = 'player' }) => {
const [playback, setPlayback] = useState<LessonPlayback | null>(null);
const [error, setError] = useState('');
const videoRef = useRef<HTMLVideoElement>(null);
const frameRef = useRef<HTMLIFrameElement>(null);
const handlers = useRef({ onTime, onEnded });
handlers.current = { onTime, onEnded };
useEffect(() => {
let cancelled = false;
setPlayback(null);
setError('');
courseApi.playback(courseId, lesson.id)
.then((response) => { if (!cancelled) setPlayback(response.data); })
.catch((reason) => { if (!cancelled) setError(reason instanceof Error ? reason.message : 'Não foi possível carregar este vídeo.'); });
return () => { cancelled = true; };
}, [courseId, lesson.id]);
// Bunny's iframe has no HTMLVideoElement; Player.js relays its playback events.
useEffect(() => {
if (!playback || playback.kind !== 'embed') return;
let disposed = false;
void loadBunnyPlayerJs().then(() => {
if (disposed || !frameRef.current || !window.playerjs) return;
const player = new window.playerjs.Player(frameRef.current);
player.on('timeupdate', (data) => {
// Bunny only saves the watched position; completion comes from its "ended" event.
if (!disposed) handlers.current.onTime(Math.floor(data?.seconds || 0));
});
player.on('ended', (data) => {
if (!disposed) handlers.current.onEnded(Math.floor(data?.duration || data?.seconds || 0), false);
});
}).catch(() => undefined);
return () => { disposed = true; };
}, [playback]);
const restorePosition = () => {
const video = videoRef.current;
if (video && resumeAt > 0 && resumeAt < video.duration - 5) video.currentTime = resumeAt;
};
let content: React.ReactNode;
if (error) {
content = <div className="pl msg"><WarningCircleIcon className="ph" size={28} /><span>{error}</span></div>;
} else if (!playback) {
content = <div className="pl msg"><CircleNotchIcon className="ph spin" size={28} /><span>Carregando vídeo</span></div>;
} else if (playback.kind === 'embed' && playback.embedUrl) {
content = (
<iframe
key={lesson.id}
ref={frameRef}
src={playback.embedUrl}
title={lesson.title || 'Vídeo da aula'}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture; fullscreen"
allowFullScreen
/>
);
} else if (playback.source) {
content = (
<video
key={lesson.id}
ref={videoRef}
src={playback.source}
controls
autoPlay
playsInline
onTimeUpdate={(event) => {
const { currentTime, duration } = event.currentTarget;
if (duration > 0) handlers.current.onTime(currentTime, duration);
}}
onEnded={(event) => handlers.current.onEnded(Math.round(event.currentTarget.duration || 0), true)}
onLoadedMetadata={restorePosition}
>
Seu navegador não suporta vídeo.
</video>
);
} else {
content = <div className="pl msg"><span>Vídeo indisponível.</span></div>;
}
return <div className={className}>{content}</div>;
};