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.
This commit is contained in:
129
components/course/LessonVideo.tsx
Normal file
129
components/course/LessonVideo.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
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>;
|
||||
};
|
||||
86
components/course/Materials.tsx
Normal file
86
components/course/Materials.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
ArrowSquareOutIcon, CheckIcon, CircleNotchIcon, FileIcon,
|
||||
ImageIcon, LinkSimpleIcon, VideoCameraIcon,
|
||||
} from '@phosphor-icons/react';
|
||||
import { DocMockIcon, DownloadMockIcon, PdfMockIcon, XlsMockIcon, ZipMockIcon } from '../ui/MockupIcons';
|
||||
import { Attachment, AttachmentType } from '../../types';
|
||||
import { downloadCourseAsset } from '../../services/api';
|
||||
import { recordDownloadHistory } from '../../services/db';
|
||||
import { useToast } from '../../context/ToastContext';
|
||||
import { useAuth } from '../../context/AuthContext';
|
||||
import { paths } from '../../lib/routes';
|
||||
|
||||
export const attachmentIcon = (type: AttachmentType) => {
|
||||
switch (type) {
|
||||
case 'pdf': return <PdfMockIcon className="ph" />;
|
||||
case 'spreadsheet': return <XlsMockIcon className="ph" />;
|
||||
case 'zip': return <ZipMockIcon className="ph" />;
|
||||
case 'doc': return <DocMockIcon className="ph" />;
|
||||
case 'image': return <ImageIcon className="ph" />;
|
||||
case 'link': return <LinkSimpleIcon className="ph" />;
|
||||
case 'video': return <VideoCameraIcon className="ph" />;
|
||||
default: return <FileIcon className="ph" />;
|
||||
}
|
||||
};
|
||||
|
||||
export const attachmentLabel = (type: AttachmentType) => ({
|
||||
pdf: 'PDF', spreadsheet: 'Planilha', zip: 'ZIP', doc: 'Documento', image: 'Imagem', link: 'Link', video: 'Vídeo',
|
||||
}[type] || 'Arquivo');
|
||||
|
||||
/** Downloads through the Academy (or opens a link) with the same feedback as before. */
|
||||
export const useMaterialAction = () => {
|
||||
const { showDownloadToast, showToast } = useToast();
|
||||
const { user } = useAuth();
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
const [doneId, setDoneId] = useState<string | null>(null);
|
||||
|
||||
const open = async (attachment: Attachment) => {
|
||||
if (attachment.type === 'link') {
|
||||
showToast(`Abrindo “${attachment.name}”.`, 'info');
|
||||
window.open(attachment.url, '_blank', 'noopener,noreferrer');
|
||||
if (user) void recordDownloadHistory(attachment.id).catch(() => undefined);
|
||||
return false;
|
||||
}
|
||||
setBusyId(attachment.id);
|
||||
try {
|
||||
await downloadCourseAsset(attachment.id, attachment.name);
|
||||
showDownloadToast(attachment.name, attachment.size);
|
||||
if (user) void recordDownloadHistory(attachment.id).catch(() => undefined);
|
||||
setDoneId(attachment.id);
|
||||
window.setTimeout(() => setDoneId((current) => (current === attachment.id ? null : current)), 3000);
|
||||
return true;
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Não foi possível baixar este material.', 'error');
|
||||
return false;
|
||||
} finally {
|
||||
setBusyId(null);
|
||||
}
|
||||
};
|
||||
|
||||
return { open, busyId, doneId };
|
||||
};
|
||||
|
||||
export const MaterialButton: React.FC<{ attachment: Attachment; action: ReturnType<typeof useMaterialAction>; label?: boolean; className?: string }> = ({ attachment, action, label = true, className = 'btn sec' }) => {
|
||||
const { user } = useAuth();
|
||||
if (!user) return label ? <Link className={className} to={paths.signIn}>Entrar para baixar</Link> : null;
|
||||
const isLink = attachment.type === 'link';
|
||||
const busy = action.busyId === attachment.id;
|
||||
const done = action.doneId === attachment.id;
|
||||
const icon = busy ? <CircleNotchIcon className="ph spin" /> : done ? <CheckIcon className="ph" /> : isLink ? <ArrowSquareOutIcon className="ph" /> : <DownloadMockIcon className="ph" />;
|
||||
const text = isLink ? 'Abrir' : done ? 'Baixado' : 'Baixar';
|
||||
return (
|
||||
<button type="button" className={className} onClick={() => void action.open(attachment)} disabled={busy} aria-label={`${text} ${attachment.name}`}>
|
||||
{icon}{label && ` ${text}`}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
export const MaterialRow: React.FC<{ attachment: Attachment; detail?: string; action: ReturnType<typeof useMaterialAction>; compact?: boolean }> = ({ attachment, detail, action, compact }) => (
|
||||
<div className="file" style={compact ? { paddingBlock: 8 } : undefined}>
|
||||
<span className="ic">{attachmentIcon(attachment.type)}</span>
|
||||
<span>{attachment.name}<small className="num">{[detail, attachmentLabel(attachment.type), attachment.size].filter(Boolean).join(' · ')}</small></span>
|
||||
{compact ? <MaterialButton attachment={attachment} action={action} label={false} className="iconbtn" /> : <MaterialButton attachment={attachment} action={action} />}
|
||||
</div>
|
||||
);
|
||||
Reference in New Issue
Block a user