Combined view works with courses / lessons

This commit is contained in:
austinkelsay 2024-11-20 17:46:52 -06:00
parent 293d6d2eeb
commit 2ba4615885
No known key found for this signature in database
GPG Key ID: 44CB4EC6D9F2FA02
3 changed files with 280 additions and 4 deletions

View File

@ -0,0 +1,259 @@
import React, { useEffect, useState, useRef, useCallback } from "react";
import { Tag } from "primereact/tag";
import Image from "next/image";
import ZapDisplay from "@/components/zaps/ZapDisplay";
import { useImageProxy } from "@/hooks/useImageProxy";
import { useZapsQuery } from "@/hooks/nostrQueries/zaps/useZapsQuery";
import GenericButton from "@/components/buttons/GenericButton";
import { nip19 } from "nostr-tools";
import { Divider } from "primereact/divider";
import { getTotalFromZaps } from "@/utils/lightning";
import dynamic from "next/dynamic";
import useWindowWidth from "@/hooks/useWindowWidth";
import appConfig from "@/config/appConfig";
import useTrackVideoLesson from '@/hooks/tracking/useTrackVideoLesson';
const MDDisplay = dynamic(
() => import("@uiw/react-markdown-preview"),
{
ssr: false,
}
);
const CombinedLesson = ({ lesson, course, decryptionPerformed, isPaid, setCompleted }) => {
const [zapAmount, setZapAmount] = useState(0);
const [nAddress, setNAddress] = useState(null);
const [videoDuration, setVideoDuration] = useState(null);
const [videoPlayed, setVideoPlayed] = useState(false);
const mdDisplayRef = useRef(null);
const { zaps, zapsLoading, zapsError } = useZapsQuery({ event: lesson, type: "lesson" });
const { returnImageProxy } = useImageProxy();
const windowWidth = useWindowWidth();
const isMobileView = windowWidth <= 768;
const isVideo = lesson?.type === 'video';
const { isCompleted: videoCompleted, isTracking: videoTracking } = useTrackVideoLesson({
lessonId: lesson?.d,
videoDuration,
courseId: course?.d,
videoPlayed,
paidCourse: isPaid,
decryptionPerformed
});
useEffect(() => {
const handleYouTubeMessage = (event) => {
if (event.origin !== "https://www.youtube.com") return;
try {
const data = JSON.parse(event.data);
if (data.event === "onReady") {
event.source.postMessage('{"event":"listening"}', "https://www.youtube.com");
} else if (data.event === "infoDelivery" && data?.info?.currentTime) {
setVideoPlayed(true);
setVideoDuration(data.info?.progressState?.duration);
}
} catch (error) {
console.error("Error parsing YouTube message:", error);
}
};
if (isVideo) {
window.addEventListener("message", handleYouTubeMessage);
return () => window.removeEventListener("message", handleYouTubeMessage);
}
}, [isVideo]);
const checkDuration = useCallback(() => {
if (!isVideo) return;
const videoElement = mdDisplayRef.current?.querySelector('video');
const youtubeIframe = mdDisplayRef.current?.querySelector('iframe[src*="youtube.com"]');
if (videoElement && videoElement.readyState >= 1) {
setVideoDuration(Math.round(videoElement.duration));
setVideoPlayed(true);
} else if (youtubeIframe) {
youtubeIframe.contentWindow.postMessage('{"event":"listening"}', '*');
}
}, [isVideo]);
useEffect(() => {
if (!zaps || zapsLoading || zapsError) return;
const total = getTotalFromZaps(zaps, lesson);
setZapAmount(total);
}, [zaps, zapsLoading, zapsError, lesson]);
useEffect(() => {
if (lesson) {
const addr = nip19.naddrEncode({
pubkey: lesson.pubkey,
kind: lesson.kind,
identifier: lesson.d,
relays: appConfig.defaultRelayUrls
});
setNAddress(addr);
}
}, [lesson]);
useEffect(() => {
if (decryptionPerformed && isPaid) {
const timer = setTimeout(checkDuration, 500);
return () => clearTimeout(timer);
} else {
const timer = setTimeout(checkDuration, 3000);
return () => clearTimeout(timer);
}
}, [decryptionPerformed, isPaid, checkDuration]);
useEffect(() => {
if (isVideo && videoCompleted && !videoTracking) {
setCompleted(lesson.id);
}
}, [videoCompleted, videoTracking, lesson.id, setCompleted, isVideo]);
const renderContent = () => {
if (isPaid && decryptionPerformed) {
return (
<div ref={mdDisplayRef}>
<MDDisplay className={`${isVideo ? 'p-0' : 'p-2'} rounded-lg w-full`} source={lesson.content} />
</div>
);
}
if (isPaid && !decryptionPerformed) {
if (isVideo) {
return (
<div className="w-full aspect-video rounded-lg flex flex-col items-center justify-center relative overflow-hidden">
<div
className="absolute inset-0 opacity-50"
style={{
backgroundImage: `url(${lesson.image})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
}}
></div>
<div className="absolute inset-0 bg-black bg-opacity-50"></div>
<div className="mx-auto py-auto z-10">
<i className="pi pi-lock text-[100px] text-red-500"></i>
</div>
<p className="text-center text-xl text-red-500 z-10 mt-4">
This content is paid and needs to be purchased before viewing.
</p>
</div>
);
}
return (
<div className="w-full p-8 rounded-lg flex flex-col items-center justify-center bg-gray-100 dark:bg-gray-800">
<div className="mx-auto py-auto">
<i className="pi pi-lock text-[60px] text-red-500"></i>
</div>
<p className="text-center text-xl text-red-500 mt-4">
This content is paid and needs to be purchased before viewing.
</p>
</div>
);
}
if (lesson?.content) {
return (
<div ref={mdDisplayRef}>
<MDDisplay className={`${isVideo ? 'p-0' : 'p-2'} rounded-lg w-full`} source={lesson.content} />
</div>
);
}
return null;
};
return (
<div className="w-full">
{isVideo ? renderContent() : (
<>
<div className="relative w-[80%] h-[200px] mx-auto mb-24">
<Image
alt="lesson background image"
src={returnImageProxy(lesson.image)}
fill
className="object-cover"
/>
<div className="absolute inset-0 bg-black bg-opacity-20"></div>
</div>
</>
)}
<div className={`${isVideo ? 'bg-gray-800/90 rounded-lg p-4 m-4' : 'w-full mx-auto px-4 py-8 -mt-32 relative z-10'}`}>
<div className={`${!isVideo && 'mb-8 bg-gray-800/70 rounded-lg p-4'}`}>
<div className="flex flex-row items-center justify-between w-full">
<h1 className='text-3xl font-bold text-white'>{lesson.title}</h1>
<div className="flex flex-wrap gap-2">
{lesson.topics && lesson.topics.length > 0 && (
lesson.topics.map((topic, index) => (
<Tag className='text-white' key={index} value={topic}></Tag>
))
)}
</div>
</div>
<div className='text-xl text-gray-200 mb-4 mt-4'>{lesson.summary && (
<div className="text-xl mt-4">
{lesson.summary.split('\n').map((line, index) => (
<p key={index}>{line}</p>
))}
</div>
)}
</div>
<div className='flex items-center justify-between'>
<div className='flex items-center'>
<Image
alt="avatar image"
src={returnImageProxy(lesson.author?.avatar, lesson.author?.username)}
width={50}
height={50}
className="rounded-full mr-4"
/>
<p className='text-lg text-white'>
By{' '}
<a rel='noreferrer noopener' target='_blank' className='text-blue-300 hover:underline'>
{lesson.author?.username || lesson.author?.name || lesson.author?.pubkey}
</a>
</p>
</div>
<ZapDisplay
zapAmount={zapAmount}
event={lesson}
zapsLoading={zapsLoading}
/>
</div>
<div className="w-full flex flex-row justify-end">
<GenericButton
tooltip={isMobileView ? null : "View Nostr Note"}
tooltipOptions={{ position: 'left' }}
icon="pi pi-external-link"
outlined
onClick={() => {
window.open(`https://habla.news/a/${nAddress}`, '_blank');
}}
/>
</div>
</div>
{!isVideo && <Divider />}
{lesson?.additionalLinks && lesson.additionalLinks.length > 0 && (
<div className='mt-6 bg-gray-800/90 rounded-lg p-4'>
<h3 className='text-lg font-semibold mb-2 text-white'>External links:</h3>
<ul className='list-disc list-inside text-white'>
{lesson.additionalLinks.map((link, index) => (
<li key={index}>
<a href={link} target="_blank" rel="noopener noreferrer" className='text-blue-300 hover:underline'>
{new URL(link).hostname}
</a>
</li>
))}
</ul>
</div>
)}
</div>
{!isVideo && renderContent()}
</div>
);
};
export default CombinedLesson;

View File

@ -67,6 +67,11 @@ const LessonSelector = ({ isPaidCourse, lessons, setLessons, allContent, onNewRe
value: content
}));
const combinedOptions = filteredContent.filter(content => content?.topics?.includes('video') && content?.topics?.includes('document') && content.kind).map(content => ({
label: content.title,
value: content
}));
setContentOptions([
{
label: 'Draft Documents',
@ -83,6 +88,10 @@ const LessonSelector = ({ isPaidCourse, lessons, setLessons, allContent, onNewRe
{
label: 'Published Videos',
items: videoOptions
},
{
label: 'Published Combined',
items: combinedOptions
}
]);
};

View File

@ -4,6 +4,7 @@ import { parseCourseEvent, parseEvent, findKind0Fields } from "@/utils/nostr";
import CourseDetails from "@/components/content/courses/CourseDetails";
import VideoLesson from "@/components/content/courses/VideoLesson";
import DocumentLesson from "@/components/content/courses/DocumentLesson";
import CombinedLesson from "@/components/content/courses/CombinedLesson";
import { useNDKContext } from "@/context/NDKContext";
import { useSession } from 'next-auth/react';
import axios from "axios";
@ -225,6 +226,16 @@ const Course = () => {
);
}
const renderLesson = (lesson) => {
if (lesson.topics?.includes('video') && lesson.topics?.includes('document')) {
return <CombinedLesson lesson={lesson} course={course} decryptionPerformed={decryptionPerformed} isPaid={paidCourse} setCompleted={setCompleted} />;
} else if (lesson.type === 'video' && !lesson.topics?.includes('document')) {
return <VideoLesson lesson={lesson} course={course} decryptionPerformed={decryptionPerformed} isPaid={paidCourse} setCompleted={setCompleted} />;
} else if (lesson.type === 'document' && !lesson.topics?.includes('video')) {
return <DocumentLesson lesson={lesson} course={course} decryptionPerformed={decryptionPerformed} isPaid={paidCourse} setCompleted={setCompleted} />;
}
}
return (
<>
{course && paidCourse !== null && (
@ -260,10 +271,7 @@ const Course = () => {
}
>
<div className="w-full py-4 rounded-b-lg">
{lesson.type === 'video' ?
<VideoLesson lesson={lesson} course={course} decryptionPerformed={decryptionPerformed} isPaid={paidCourse} setCompleted={setCompleted} /> :
<DocumentLesson lesson={lesson} course={course} decryptionPerformed={decryptionPerformed} isPaid={paidCourse} setCompleted={setCompleted} />
}
{renderLesson(lesson)}
</div>
</AccordionTab>
))}