feat: Implement ZapThreads with access control for paid content - Add to CourseDetails, CourseTemplate, CourseLesson - Block comments for unpaid users - Allow comments for free content and authorized paid users

This commit is contained in:
kiwihodl 2025-04-02 12:16:11 -05:00
parent fede031fe9
commit 466ead359b
No known key found for this signature in database
GPG Key ID: A2878DC38F1E643C
5 changed files with 784 additions and 443 deletions

View File

@ -1,58 +1,100 @@
import React, { useEffect, useRef } from 'react'; import React, { useEffect, useRef } from "react";
const ZapThreadsWrapper = ({ anchor, user, relays, disable, className }) => { const ZapThreadsWrapper = ({
anchor,
user,
relays,
disable,
className,
isAuthorized,
}) => {
// Create a ref to store the reference to the <div> element // Create a ref to store the reference to the <div> element
const zapRef = useRef(null); const zapRef = useRef(null);
useEffect(() => { useEffect(() => {
// Only load the script if the user is authorized
if (!isAuthorized) {
return;
}
// Create a new <script> element // Create a new <script> element
const script = document.createElement('script'); const script = document.createElement("script");
// Set the source URL of the script to load the ZapThreads library // Set the source URL of the script to load the ZapThreads library
script.src = 'https://unpkg.com/zapthreads/dist/zapthreads.iife.js'; script.src = "https://unpkg.com/zapthreads/dist/zapthreads.iife.js";
// Set the script to load asynchronously // Set the script to load asynchronously
script.async = true; script.async = true;
// Function to handle the script load event // Function to handle the script load event
const handleScriptLoad = () => { const handleScriptLoad = () => {
// Create a new <zap-threads> element // Create a new <zap-threads> element
const zapElement = document.createElement('zap-threads'); const zapElement = document.createElement("zap-threads");
zapElement.setAttribute('anchor', anchor); zapElement.setAttribute("anchor", anchor);
if (user) zapElement.setAttribute('user', user);
zapElement.setAttribute('relays', relays.replace(/\s/g, ''));
if (disable) zapElement.setAttribute('disable', disable);
// Remove any existing <zap-threads> element before appending a new one // Only set user if it exists and is not null
if (zapRef.current && zapRef.current.firstChild) { if (user) {
zapRef.current.removeChild(zapRef.current.firstChild); zapElement.setAttribute("user", user);
} }
// Append the new <zap-threads> element to the <div> referenced by zapRef // Clean up relay URLs
const cleanRelays = relays
.split(",")
.map((relay) => relay.trim())
.filter((relay) => relay)
.join(",");
zapElement.setAttribute("relays", cleanRelays);
// Always set disable attribute, even if empty
zapElement.setAttribute("disable", disable || "");
// Add error handling
zapElement.addEventListener("error", (e) => {
console.error("ZapThreads error:", e);
});
// Remove any existing <zap-threads> element
if (zapRef.current) {
while (zapRef.current.firstChild) {
zapRef.current.removeChild(zapRef.current.firstChild);
}
}
// Append the new element
if (zapRef.current) { if (zapRef.current) {
zapRef.current.appendChild(zapElement); zapRef.current.appendChild(zapElement);
} }
}; };
// Attach the handleScriptLoad function to the script's load event // Attach the handleScriptLoad function to the script's load event
script.addEventListener('load', handleScriptLoad); script.addEventListener("load", handleScriptLoad);
script.addEventListener("error", (e) => {
console.error("Failed to load ZapThreads script:", e);
});
// Append the <script> element to the <body> of the document // Append the <script> element to the <body> of the document
document.body.appendChild(script); document.body.appendChild(script);
// Cleanup function to remove the <zap-threads> element and the <script> element when the component is unmounted // Cleanup function to remove the <zap-threads> element and the <script> element when the component is unmounted
return () => { return () => {
// Remove the <zap-threads> element from the <div> referenced by zapRef if (zapRef.current) {
if (zapRef.current && zapRef.current.firstChild) { while (zapRef.current.firstChild) {
zapRef.current.removeChild(zapRef.current.firstChild); zapRef.current.removeChild(zapRef.current.firstChild);
}
} }
// Remove the <script> element from the <body> of the document // Remove the <script> element from the <body> of the document
document.body.removeChild(script); document.body.removeChild(script);
// Remove the load event listener from the script // Remove the load event listener from the script
script.removeEventListener('load', handleScriptLoad); script.removeEventListener("load", handleScriptLoad);
}; };
}, [anchor, user, relays, disable]); }, [anchor, user, relays, disable, isAuthorized]);
if (!isAuthorized) {
return null;
}
// Render a <div> element and attach the zapRef to it // Render a <div> element and attach the zapRef to it
return <div className={`overflow-x-hidden ${className || ''}`} ref={zapRef} />; return (
<div className={`overflow-x-hidden ${className || ""}`} ref={zapRef} />
);
}; };
export default ZapThreadsWrapper; export default ZapThreadsWrapper;

View File

@ -1,9 +1,17 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Tag } from "primereact/tag"; import { Tag } from "primereact/tag";
import ZapDisplay from "@/components/zaps/ZapDisplay"; import ZapDisplay from "@/components/zaps/ZapDisplay";
import ZapThreadsWrapper from "@/components/ZapThreadsWrapper";
import { nip19 } from "nostr-tools"; import { nip19 } from "nostr-tools";
import Image from "next/image" import Image from "next/image";
import { useZapsSubscription } from "@/hooks/nostrQueries/zaps/useZapsSubscription"; import { useZapsSubscription } from "@/hooks/nostrQueries/zaps/useZapsSubscription";
import { getTotalFromZaps } from "@/utils/lightning"; import { getTotalFromZaps } from "@/utils/lightning";
import { useImageProxy } from "@/hooks/useImageProxy"; import { useImageProxy } from "@/hooks/useImageProxy";
@ -15,16 +23,22 @@ import useWindowWidth from "@/hooks/useWindowWidth";
import GenericButton from "@/components/buttons/GenericButton"; import GenericButton from "@/components/buttons/GenericButton";
import appConfig from "@/config/appConfig"; import appConfig from "@/config/appConfig";
import { BookOpen } from "lucide-react"; import { BookOpen } from "lucide-react";
import { useSession } from "next-auth/react";
export function CourseTemplate({ course, showMetaTags = true }) { export function CourseTemplate({ course, showMetaTags = true }) {
const { zaps, zapsLoading, zapsError } = useZapsSubscription({ event: course }); const { zaps, zapsLoading, zapsError } = useZapsSubscription({
event: course,
});
const [zapAmount, setZapAmount] = useState(0); const [zapAmount, setZapAmount] = useState(0);
const [lessonCount, setLessonCount] = useState(0); const [lessonCount, setLessonCount] = useState(0);
const [nAddress, setNAddress] = useState(null); const [nAddress, setNAddress] = useState(null);
const [npub, setNpub] = useState(null);
const [nsec, setNsec] = useState(null);
const router = useRouter(); const router = useRouter();
const { returnImageProxy } = useImageProxy(); const { returnImageProxy } = useImageProxy();
const windowWidth = useWindowWidth(); const windowWidth = useWindowWidth();
const isMobile = windowWidth < 768; const isMobile = windowWidth < 768;
const { data: session } = useSession();
useEffect(() => { useEffect(() => {
if (zaps.length > 0) { if (zaps.length > 0) {
@ -35,7 +49,7 @@ export function CourseTemplate({ course, showMetaTags = true }) {
useEffect(() => { useEffect(() => {
if (course && course?.tags) { if (course && course?.tags) {
const lessons = course.tags.filter(tag => tag[0] === "a"); const lessons = course.tags.filter((tag) => tag[0] === "a");
setLessonCount(lessons.length); setLessonCount(lessons.length);
} }
}, [course]); }, [course]);
@ -46,26 +60,44 @@ export function CourseTemplate({ course, showMetaTags = true }) {
pubkey: course.pubkey, pubkey: course.pubkey,
kind: course.kind, kind: course.kind,
identifier: course.d, identifier: course.d,
relays: appConfig.defaultRelayUrls relays: appConfig.defaultRelayUrls,
}); });
setNAddress(nAddress); setNAddress(nAddress);
} }
}, [course]); }, [course]);
useEffect(() => {
if (session?.user?.privkey) {
const privkeyBuffer = Buffer.from(session.user.privkey, "hex");
setNsec(nip19.nsecEncode(privkeyBuffer));
} else if (session?.user?.pubkey) {
setNpub(nip19.npubEncode(session.user.pubkey));
}
}, [session]);
const shouldShowMetaTags = (topic) => { const shouldShowMetaTags = (topic) => {
if (!showMetaTags) { if (!showMetaTags) {
return !["lesson", "document", "video", "course"].includes(topic); return !["lesson", "document", "video", "course"].includes(topic);
} }
return true; return true;
} };
if (!nAddress) return <div className='w-full h-full flex items-center justify-center'><ProgressSpinner /></div> if (!nAddress)
return (
<div className="w-full h-full flex items-center justify-center">
<ProgressSpinner />
</div>
);
if (zapsError) return <div>Error: {zapsError}</div>; if (zapsError) return <div>Error: {zapsError}</div>;
return ( return (
<Card className="overflow-hidden group hover:shadow-xl transition-all duration-300 bg-gray-800 m-2 border-none"> <Card className="overflow-hidden group hover:shadow-xl transition-all duration-300 bg-gray-800 m-2 border-none">
<div className="relative w-full h-0 hover:opacity-70 cursor-pointer" style={{ paddingBottom: "56.25%" }} onClick={() => router.push(`/course/${nAddress}`)}> <div
className="relative w-full h-0 hover:opacity-70 cursor-pointer"
style={{ paddingBottom: "56.25%" }}
onClick={() => router.push(`/course/${nAddress}`)}
>
<Image <Image
alt="video thumbnail" alt="video thumbnail"
src={returnImageProxy(course.image)} src={returnImageProxy(course.image)}
@ -81,47 +113,125 @@ export function CourseTemplate({ course, showMetaTags = true }) {
</div> </div>
<CardHeader className="flex flex-row justify-between items-center p-4 border-b border-gray-700"> <CardHeader className="flex flex-row justify-between items-center p-4 border-b border-gray-700">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<CardTitle className="text-xl sm:text-2xl text-[#f8f8ff]">{course.name}</CardTitle> <CardTitle className="text-xl sm:text-2xl text-[#f8f8ff]">
{course.name}
</CardTitle>
</div> </div>
<div className="text-[#f8f8ff]"> <div className="text-[#f8f8ff]">
<ZapDisplay zapAmount={zapAmount} event={course} zapsLoading={zapsLoading && zapAmount === 0} /> <ZapDisplay
zapAmount={zapAmount}
event={course}
zapsLoading={zapsLoading && zapAmount === 0}
/>
</div> </div>
</CardHeader> </CardHeader>
<CardContent className={`${isMobile ? "px-3" : ""} pt-4 pb-2 w-full flex flex-row justify-between items-center`}> <CardContent
className={`${
isMobile ? "px-3" : ""
} pt-4 pb-2 w-full flex flex-row justify-between items-center`}
>
<div className="flex flex-wrap gap-2 max-w-[65%]"> <div className="flex flex-wrap gap-2 max-w-[65%]">
{course && course.topics && course.topics.map((topic, index) => ( {course &&
shouldShowMetaTags(topic) && ( course.topics &&
<Tag size="small" key={index} className="px-2 py-1 text-sm text-[#f8f8ff]"> course.topics.map(
{topic} (topic, index) =>
</Tag> shouldShowMetaTags(topic) && (
) <Tag
))} size="small"
key={index}
className="px-2 py-1 text-sm text-[#f8f8ff]"
>
{topic}
</Tag>
)
)}
</div> </div>
{course?.price && course?.price > 0 ? ( {course?.price && course?.price > 0 ? (
<Message className={`${isMobile ? "py-1 text-xs" : "py-2"} whitespace-nowrap`} icon="pi pi-lock" severity="info" text={`${course.price} sats`} /> <Message
className={`${
isMobile ? "py-1 text-xs" : "py-2"
} whitespace-nowrap`}
icon="pi pi-lock"
severity="info"
text={`${course.price} sats`}
/>
) : ( ) : (
<Message className={`${isMobile ? "py-1 text-xs" : "py-2"} whitespace-nowrap`} icon="pi pi-lock-open" severity="success" text="Free" /> <Message
className={`${
isMobile ? "py-1 text-xs" : "py-2"
} whitespace-nowrap`}
icon="pi pi-lock-open"
severity="success"
text="Free"
/>
)} )}
</CardContent> </CardContent>
<CardDescription className={`${isMobile ? "w-full p-3" : "p-6"} py-2 pt-0 text-base text-neutral-50/90 dark:text-neutral-900/90 overflow-hidden min-h-[4em] flex items-center max-w-[100%]`} <CardDescription
style={{ className={`${
overflow: "hidden", isMobile ? "w-full p-3" : "p-6"
display: "-webkit-box", } py-2 pt-0 text-base text-neutral-50/90 dark:text-neutral-900/90 overflow-hidden min-h-[4em] flex items-center max-w-[100%]`}
WebkitBoxOrient: "vertical", style={{
WebkitLineClamp: "2" overflow: "hidden",
}}> display: "-webkit-box",
<p className="line-clamp-2 text-wrap break-words">{(course.summary || course.description)?.split('\n').map((line, index) => ( WebkitBoxOrient: "vertical",
<span className="text-wrap break-words" key={index}>{line}</span> WebkitLineClamp: "2",
))}</p> }}
>
<p className="line-clamp-2 text-wrap break-words">
{(course.summary || course.description)
?.split("\n")
.map((line, index) => (
<span className="text-wrap break-words" key={index}>
{line}
</span>
))}
</p>
</CardDescription> </CardDescription>
<CardFooter className={`flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 border-t border-gray-700 pt-4 ${isMobile ? "px-3" : ""}`}> <CardFooter
<p className="text-sm text-gray-300">{course?.published_at && course.published_at !== "" ? ( className={`flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 border-t border-gray-700 pt-4 ${
formatTimestampToHowLongAgo(course.published_at) isMobile ? "px-3" : ""
) : ( }`}
formatTimestampToHowLongAgo(course.created_at) >
)}</p> <p className="text-sm text-gray-300">
<GenericButton onClick={() => router.push(`/course/${nAddress}`)} size="small" label="Start Learning" icon="pi pi-chevron-right" iconPos="right" outlined className="items-center py-2" /> {course?.published_at && course.published_at !== ""
? formatTimestampToHowLongAgo(course.published_at)
: formatTimestampToHowLongAgo(course.created_at)}
</p>
<GenericButton
onClick={() => router.push(`/course/${nAddress}`)}
size="small"
label="Start Learning"
icon="pi pi-chevron-right"
iconPos="right"
outlined
className="items-center py-2"
/>
</CardFooter> </CardFooter>
{nAddress !== null &&
(!course?.price ||
course.price === 0 ||
session?.user?.role?.subscribed ||
session?.user?.purchased?.some(
(purchase) => purchase.resourceId === course.d
)) && (
<div className="px-4 pb-4">
{nsec || npub ? (
<ZapThreadsWrapper
anchor={nAddress}
user={nsec || npub || null}
relays={appConfig.defaultRelayUrls.join(",")}
disable="zaps"
/>
) : (
<ZapThreadsWrapper
anchor={nAddress}
user={npub}
relays={appConfig.defaultRelayUrls.join(",")}
disable="zaps"
/>
)}
</div>
)}
</Card> </Card>
) );
} }

View File

@ -1,216 +1,332 @@
import React, { useEffect, useState, useCallback, useRef } from 'react'; import React, { useEffect, useState, useCallback, useRef } from "react";
import axios from 'axios'; import axios from "axios";
import { useToast } from "@/hooks/useToast"; import { useToast } from "@/hooks/useToast";
import { Tag } from 'primereact/tag'; import { Tag } from "primereact/tag";
import Image from 'next/image'; import Image from "next/image";
import { useRouter } from 'next/router'; import { useRouter } from "next/router";
import CoursePaymentButton from "@/components/bitcoinConnect/CoursePaymentButton"; import CoursePaymentButton from "@/components/bitcoinConnect/CoursePaymentButton";
import ZapDisplay from '@/components/zaps/ZapDisplay'; import ZapDisplay from "@/components/zaps/ZapDisplay";
import GenericButton from '@/components/buttons/GenericButton'; import GenericButton from "@/components/buttons/GenericButton";
import { nip19 } from 'nostr-tools'; import { nip19 } from "nostr-tools";
import { useImageProxy } from '@/hooks/useImageProxy'; import { useImageProxy } from "@/hooks/useImageProxy";
import { useZapsSubscription } from '@/hooks/nostrQueries/zaps/useZapsSubscription'; import { useZapsSubscription } from "@/hooks/nostrQueries/zaps/useZapsSubscription";
import { getTotalFromZaps } from '@/utils/lightning'; import { getTotalFromZaps } from "@/utils/lightning";
import { useSession } from 'next-auth/react'; import { useSession } from "next-auth/react";
import useWindowWidth from "@/hooks/useWindowWidth"; import useWindowWidth from "@/hooks/useWindowWidth";
import { useNDKContext } from "@/context/NDKContext"; import { useNDKContext } from "@/context/NDKContext";
import { findKind0Fields } from '@/utils/nostr'; import { findKind0Fields } from "@/utils/nostr";
import appConfig from "@/config/appConfig"; import appConfig from "@/config/appConfig";
import useTrackCourse from '@/hooks/tracking/useTrackCourse'; import useTrackCourse from "@/hooks/tracking/useTrackCourse";
import WelcomeModal from '@/components/onboarding/WelcomeModal'; import WelcomeModal from "@/components/onboarding/WelcomeModal";
import { ProgressSpinner } from 'primereact/progressspinner'; import { ProgressSpinner } from "primereact/progressspinner";
import { Toast } from "primereact/toast"; import { Toast } from "primereact/toast";
import MoreOptionsMenu from "@/components/ui/MoreOptionsMenu"; import MoreOptionsMenu from "@/components/ui/MoreOptionsMenu";
import ZapThreadsWrapper from "@/components/ZapThreadsWrapper";
export default function CourseDetails({ processedEvent, paidCourse, lessons, decryptionPerformed, handlePaymentSuccess, handlePaymentError }) { export default function CourseDetails({
const [zapAmount, setZapAmount] = useState(0); processedEvent,
const [author, setAuthor] = useState(null); paidCourse,
const [nAddress, setNAddress] = useState(null); lessons,
const router = useRouter(); decryptionPerformed,
const { returnImageProxy } = useImageProxy(); handlePaymentSuccess,
const { zaps, zapsLoading, zapsError } = useZapsSubscription({ event: processedEvent }); handlePaymentError,
const { data: session, status } = useSession(); }) {
const { showToast } = useToast(); const [zapAmount, setZapAmount] = useState(0);
const windowWidth = useWindowWidth(); const [author, setAuthor] = useState(null);
const isMobileView = windowWidth <= 768; const [nAddress, setNAddress] = useState(null);
const { ndk } = useNDKContext(); const [nsec, setNsec] = useState(null);
const menuRef = useRef(null); const [npub, setNpub] = useState(null);
const toastRef = useRef(null); const router = useRouter();
const { returnImageProxy } = useImageProxy();
const { zaps, zapsLoading, zapsError } = useZapsSubscription({
event: processedEvent,
});
const { data: session, status } = useSession();
const { showToast } = useToast();
const windowWidth = useWindowWidth();
const isMobileView = windowWidth <= 768;
const { ndk } = useNDKContext();
const menuRef = useRef(null);
const toastRef = useRef(null);
const handleDelete = async () => { const handleDelete = async () => {
try { try {
const response = await axios.delete(`/api/courses/${processedEvent.d}`); const response = await axios.delete(`/api/courses/${processedEvent.d}`);
if (response.status === 204) { if (response.status === 204) {
showToast('success', 'Success', 'Course deleted successfully.'); showToast("success", "Success", "Course deleted successfully.");
router.push('/'); router.push("/");
} }
} catch (error) { } catch (error) {
showToast('error', 'Error', 'Failed to delete course. Please try again.'); showToast("error", "Error", "Failed to delete course. Please try again.");
} }
};
const menuItems = [
{
label: processedEvent?.pubkey === session?.user?.pubkey ? "Edit" : null,
icon: "pi pi-pencil",
command: () => router.push(`/course/${processedEvent.d}/edit`),
visible: processedEvent?.pubkey === session?.user?.pubkey,
},
{
label: processedEvent?.pubkey === session?.user?.pubkey ? "Delete" : null,
icon: "pi pi-trash",
command: handleDelete,
visible: processedEvent?.pubkey === session?.user?.pubkey,
},
{
label: "View Nostr note",
icon: "pi pi-globe",
command: () => window.open(`https://nostr.band/${nAddress}`, "_blank"),
},
];
const { isCompleted } = useTrackCourse({
courseId: processedEvent?.d,
paidCourse,
decryptionPerformed,
});
const fetchAuthor = useCallback(
async (pubkey) => {
if (!pubkey) return;
const author = await ndk.getUser({ pubkey });
const profile = await author.fetchProfile();
const fields = await findKind0Fields(profile);
if (fields) {
setAuthor(fields);
}
},
[ndk]
);
useEffect(() => {
if (processedEvent) {
const naddr = nip19.naddrEncode({
pubkey: processedEvent.pubkey,
kind: processedEvent.kind,
identifier: processedEvent.d,
relays: appConfig.defaultRelayUrls,
});
setNAddress(naddr);
}
}, [processedEvent]);
useEffect(() => {
if (processedEvent) {
fetchAuthor(processedEvent.pubkey);
}
}, [fetchAuthor, processedEvent]);
useEffect(() => {
if (zaps.length > 0) {
const total = getTotalFromZaps(zaps, processedEvent);
setZapAmount(total);
}
}, [zaps, processedEvent]);
useEffect(() => {
if (session?.user?.privkey) {
const privkeyBuffer = Buffer.from(session.user.privkey, "hex");
setNsec(nip19.nsecEncode(privkeyBuffer));
} else if (session?.user?.pubkey) {
setNpub(nip19.npubEncode(session.user.pubkey));
}
}, [session]);
const renderPaymentMessage = () => {
if (
session?.user &&
session.user?.role?.subscribed &&
decryptionPerformed
) {
return (
<GenericButton
tooltipOptions={{ position: "top" }}
tooltip={`You are subscribed so you can access all paid content`}
icon="pi pi-check"
label="Subscribed"
severity="success"
outlined
size="small"
className="cursor-default hover:opacity-100 hover:bg-transparent focus:ring-0"
/>
);
} }
const menuItems = [ if (
{ paidCourse &&
label: processedEvent?.pubkey === session?.user?.pubkey ? 'Edit' : null, decryptionPerformed &&
icon: 'pi pi-pencil', author &&
command: () => router.push(`/course/${processedEvent.d}/edit`), processedEvent?.pubkey !== session?.user?.pubkey &&
visible: processedEvent?.pubkey === session?.user?.pubkey !session?.user?.role?.subscribed
}, ) {
{ return (
label: processedEvent?.pubkey === session?.user?.pubkey ? 'Delete' : null, <GenericButton
icon: 'pi pi-trash', icon="pi pi-check"
command: handleDelete, label={`Paid`}
visible: processedEvent?.pubkey === session?.user?.pubkey severity="success"
}, outlined
{ size="small"
label: 'View Nostr note', tooltip={`You paid ${processedEvent.price} sats to access this course (or potentially less if a discount was applied)`}
icon: 'pi pi-globe', tooltipOptions={{ position: "top" }}
command: () => window.open(`https://nostr.band/${nAddress}`, '_blank') className="cursor-default hover:opacity-100 hover:bg-transparent focus:ring-0"
} />
]; );
const { isCompleted } = useTrackCourse({
courseId: processedEvent?.d,
paidCourse,
decryptionPerformed
});
const fetchAuthor = useCallback(async (pubkey) => {
if (!pubkey) return;
const author = await ndk.getUser({ pubkey });
const profile = await author.fetchProfile();
const fields = await findKind0Fields(profile);
if (fields) {
setAuthor(fields);
}
}, [ndk]);
useEffect(() => {
if (processedEvent) {
const naddr = nip19.naddrEncode({
pubkey: processedEvent.pubkey,
kind: processedEvent.kind,
identifier: processedEvent.d,
relays: appConfig.defaultRelayUrls
});
setNAddress(naddr);
}
}, [processedEvent]);
useEffect(() => {
if (processedEvent) {
fetchAuthor(processedEvent.pubkey);
}
}, [fetchAuthor, processedEvent]);
useEffect(() => {
if (zaps.length > 0) {
const total = getTotalFromZaps(zaps, processedEvent);
setZapAmount(total);
}
}, [zaps, processedEvent]);
const renderPaymentMessage = () => {
if (session?.user && session.user?.role?.subscribed && decryptionPerformed) {
return <GenericButton tooltipOptions={{ position: 'top' }} tooltip={`You are subscribed so you can access all paid content`} icon="pi pi-check" label="Subscribed" severity="success" outlined size="small" className="cursor-default hover:opacity-100 hover:bg-transparent focus:ring-0" />
}
if (paidCourse && decryptionPerformed && author && processedEvent?.pubkey !== session?.user?.pubkey && !session?.user?.role?.subscribed) {
return <GenericButton icon="pi pi-check" label={`Paid`} severity="success" outlined size="small" tooltip={`You paid ${processedEvent.price} sats to access this course (or potentially less if a discount was applied)`} tooltipOptions={{ position: 'top' }} className="cursor-default hover:opacity-100 hover:bg-transparent focus:ring-0" />
}
if (paidCourse && author && processedEvent?.pubkey === session?.user?.pubkey) {
return <GenericButton tooltipOptions={{ position: 'top' }} tooltip={`You created this paid course, users must pay ${processedEvent.price} sats to access it`} icon="pi pi-check" label={`Price ${processedEvent.price} sats`} severity="success" outlined size="small" className="cursor-default hover:opacity-100 hover:bg-transparent focus:ring-0" />
}
if (paidCourse && !decryptionPerformed) {
return (
<div className='w-fit'>
<CoursePaymentButton
lnAddress={author?.lud16}
amount={processedEvent.price}
onSuccess={handlePaymentSuccess}
onError={handlePaymentError}
courseId={processedEvent.d}
/>
</div>
);
}
return null;
};
if (!processedEvent || !author) {
return <div className='w-full h-full flex items-center justify-center'><ProgressSpinner /></div>;
} }
return ( if (
<div className="w-full"> paidCourse &&
<Toast ref={toastRef} /> author &&
<WelcomeModal /> processedEvent?.pubkey === session?.user?.pubkey
<div className="relative w-full h-[400px] mb-8"> ) {
<Image return (
alt="course image" <GenericButton
src={returnImageProxy(processedEvent.image)} tooltipOptions={{ position: "top" }}
fill tooltip={`You created this paid course, users must pay ${processedEvent.price} sats to access it`}
className="object-cover rounded-b-lg" icon="pi pi-check"
/> label={`Price ${processedEvent.price} sats`}
<div className="absolute inset-0 bg-black bg-opacity-20"></div> severity="success"
</div> outlined
<div className="w-full mx-auto px-4 py-8 -mt-32 relative z-10 max-mob:px-0 max-tab:px-0"> size="small"
<i className={`pi pi-arrow-left cursor-pointer hover:opacity-75 absolute top-0 left-4`} onClick={() => router.push('/')} /> className="cursor-default hover:opacity-100 hover:bg-transparent focus:ring-0"
<div className="mb-8 bg-gray-800/70 rounded-lg p-4 max-mob:rounded-t-none max-tab:rounded-t-none"> />
{isCompleted && <Tag severity="success" value="Completed" />} );
<div className="flex flex-row items-center justify-between w-full"> }
<h1 className='text-4xl font-bold text-white'>{processedEvent.name}</h1>
<ZapDisplay if (paidCourse && !decryptionPerformed) {
zapAmount={zapAmount} return (
event={processedEvent} <div className="w-fit">
zapsLoading={zapsLoading && zapAmount === 0} <CoursePaymentButton
/> lnAddress={author?.lud16}
</div> amount={processedEvent.price}
<div className="flex flex-wrap gap-2 mt-2 mb-4"> onSuccess={handlePaymentSuccess}
{processedEvent.topics && processedEvent.topics.length > 0 && ( onError={handlePaymentError}
processedEvent.topics.map((topic, index) => ( courseId={processedEvent.d}
<Tag className='text-white' key={index} value={topic}></Tag> />
))
)}
</div>
<div className='text-xl text-gray-200 mb-4 mt-4 max-mob:text-base'>{processedEvent.description && (
processedEvent.description.split('\n').map((line, index) => (
<p key={index}>{line}</p>
))
)}
</div>
<div className='flex items-center justify-between mt-8'>
<div className='flex items-center'>
<Image
alt="avatar image"
src={returnImageProxy(author?.avatar, author?.pubkey)}
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'>
{author?.username || author?.name || author?.pubkey}
</a>
</p>
</div>
<div className="flex justify-end">
<MoreOptionsMenu
menuItems={menuItems}
additionalLinks={processedEvent?.additionalLinks || []}
isMobileView={isMobileView}
/>
</div>
</div>
<div className='w-full mt-4'>
{renderPaymentMessage()}
</div>
</div>
</div>
</div> </div>
);
}
return null;
};
if (!processedEvent || !author) {
return (
<div className="w-full h-full flex items-center justify-center">
<ProgressSpinner />
</div>
); );
}
return (
<div className="w-full">
<Toast ref={toastRef} />
<WelcomeModal />
<div className="relative w-full h-[400px] mb-8">
<Image
alt="course image"
src={returnImageProxy(processedEvent.image)}
fill
className="object-cover rounded-b-lg"
/>
<div className="absolute inset-0 bg-black bg-opacity-20"></div>
</div>
<div className="w-full mx-auto px-4 py-8 -mt-32 relative z-10 max-mob:px-0 max-tab:px-0">
<i
className={`pi pi-arrow-left cursor-pointer hover:opacity-75 absolute top-0 left-4`}
onClick={() => router.push("/")}
/>
<div className="mb-8 bg-gray-800/70 rounded-lg p-4 max-mob:rounded-t-none max-tab:rounded-t-none">
{isCompleted && <Tag severity="success" value="Completed" />}
<div className="flex flex-row items-center justify-between w-full">
<h1 className="text-4xl font-bold text-white">
{processedEvent.name}
</h1>
<ZapDisplay
zapAmount={zapAmount}
event={processedEvent}
zapsLoading={zapsLoading && zapAmount === 0}
/>
</div>
<div className="flex flex-wrap gap-2 mt-2 mb-4">
{processedEvent.topics &&
processedEvent.topics.length > 0 &&
processedEvent.topics.map((topic, index) => (
<Tag className="text-white" key={index} value={topic}></Tag>
))}
</div>
<div className="text-xl text-gray-200 mb-4 mt-4 max-mob:text-base">
{processedEvent.description &&
processedEvent.description
.split("\n")
.map((line, index) => <p key={index}>{line}</p>)}
</div>
<div className="flex items-center justify-between mt-8">
<div className="flex items-center">
<Image
alt="avatar image"
src={returnImageProxy(author?.avatar, author?.pubkey)}
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"
>
{author?.username || author?.name || author?.pubkey}
</a>
</p>
</div>
<div className="flex justify-end">
<MoreOptionsMenu
menuItems={menuItems}
additionalLinks={processedEvent?.additionalLinks || []}
isMobileView={isMobileView}
/>
</div>
</div>
<div className="w-full mt-4">{renderPaymentMessage()}</div>
</div>
{nAddress !== null && (
<div className="px-4">
{paidCourse ? (
// For paid content, only show ZapThreads if user has access
processedEvent?.pubkey === session?.user?.pubkey ||
decryptionPerformed ||
session?.user?.role?.subscribed ? (
<ZapThreadsWrapper
anchor={nAddress}
user={session?.user ? nsec || npub : null}
relays={appConfig.defaultRelayUrls.join(",")}
disable="zaps"
isAuthorized={true}
/>
) : (
<div className="text-center p-4 bg-gray-800/50 rounded-lg">
<p className="text-gray-400">
Comments are only available to course purchasers,
subscribers, and the course creator.
</p>
</div>
)
) : (
// For free content, show ZapThreads to everyone
<ZapThreadsWrapper
anchor={nAddress}
user={session?.user ? nsec || npub : null}
relays={appConfig.defaultRelayUrls.join(",")}
disable="zaps"
isAuthorized={true}
/>
)}
</div>
)}
</div>
</div>
);
} }

View File

@ -13,198 +13,271 @@ import { nip19 } from "nostr-tools";
import appConfig from "@/config/appConfig"; import appConfig from "@/config/appConfig";
import MoreOptionsMenu from "@/components/ui/MoreOptionsMenu"; import MoreOptionsMenu from "@/components/ui/MoreOptionsMenu";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
import ZapThreadsWrapper from "@/components/ZapThreadsWrapper";
const MDDisplay = dynamic( const MDDisplay = dynamic(() => import("@uiw/react-markdown-preview"), {
() => import("@uiw/react-markdown-preview"), ssr: false,
{ });
ssr: false,
}
);
const CourseLesson = ({ lesson, course, decryptionPerformed, isPaid, setCompleted }) => { const CourseLesson = ({
const [zapAmount, setZapAmount] = useState(0); lesson,
const { zaps, zapsLoading, zapsError } = useZapsQuery({ event: lesson, type: "lesson" }); course,
const { returnImageProxy } = useImageProxy(); decryptionPerformed,
const menuRef = useRef(null); isPaid,
const toastRef = useRef(null); setCompleted,
const windowWidth = useWindowWidth(); }) => {
const isMobileView = windowWidth <= 768; const [zapAmount, setZapAmount] = useState(0);
const { data: session } = useSession(); const [nAddress, setNAddress] = useState(null);
const [nsec, setNsec] = useState(null);
const readTime = lesson?.content ? Math.max(30, Math.ceil(lesson.content.length / 20)) : 60; const [npub, setNpub] = useState(null);
const { zaps, zapsLoading, zapsError } = useZapsQuery({
const { isCompleted, isTracking, markLessonAsCompleted } = useTrackDocumentLesson({ event: lesson,
lessonId: lesson?.d, type: "lesson",
courseId: course?.d, });
readTime, const { returnImageProxy } = useImageProxy();
paidCourse: isPaid, const menuRef = useRef(null);
decryptionPerformed const toastRef = useRef(null);
const windowWidth = useWindowWidth();
const isMobileView = windowWidth <= 768;
const { data: session } = useSession();
const readTime = lesson?.content
? Math.max(30, Math.ceil(lesson.content.length / 20))
: 60;
const { isCompleted, isTracking, markLessonAsCompleted } =
useTrackDocumentLesson({
lessonId: lesson?.d,
courseId: course?.d,
readTime,
paidCourse: isPaid,
decryptionPerformed,
}); });
const buildMenuItems = () => { const buildMenuItems = () => {
const items = []; const items = [];
const hasAccess = session?.user && ( const hasAccess =
!isPaid || session?.user &&
decryptionPerformed || (!isPaid || decryptionPerformed || session.user.role?.subscribed);
session.user.role?.subscribed
); if (hasAccess) {
items.push({
if (hasAccess) { label: "Mark as completed",
items.push({ icon: "pi pi-check-circle",
label: 'Mark as completed', command: async () => {
icon: 'pi pi-check-circle', try {
command: async () => { await markLessonAsCompleted();
try { setCompleted && setCompleted(lesson.id);
await markLessonAsCompleted(); toastRef.current.show({
setCompleted && setCompleted(lesson.id); severity: "success",
toastRef.current.show({ summary: "Success",
severity: 'success', detail: "Lesson marked as completed",
summary: 'Success', life: 3000,
detail: 'Lesson marked as completed',
life: 3000
});
} catch (error) {
console.error('Failed to mark lesson as completed:', error);
toastRef.current.show({
severity: 'error',
summary: 'Error',
detail: 'Failed to mark lesson as completed',
life: 3000
});
}
}
}); });
} } catch (error) {
console.error("Failed to mark lesson as completed:", error);
items.push({ toastRef.current.show({
label: 'Open lesson', severity: "error",
icon: 'pi pi-arrow-up-right', summary: "Error",
command: () => { detail: "Failed to mark lesson as completed",
window.open(`/details/${lesson.id}`, '_blank'); life: 3000,
} });
}); }
},
items.push({ });
label: 'View Nostr note',
icon: 'pi pi-globe',
command: () => {
if (lesson?.d) {
const addr = nip19.naddrEncode({
pubkey: lesson.pubkey,
kind: lesson.kind,
identifier: lesson.d,
relays: appConfig.defaultRelayUrls || []
});
window.open(`https://habla.news/a/${addr}`, '_blank');
}
}
});
return items;
};
useEffect(() => {
if (!zaps || zapsLoading || zapsError) return;
const total = getTotalFromZaps(zaps, lesson);
setZapAmount(total);
}, [zaps, zapsLoading, zapsError, lesson]);
useEffect(() => {
if (isCompleted && !isTracking && setCompleted) {
setCompleted(lesson.id);
}
}, [isCompleted, isTracking, lesson.id, setCompleted]);
const renderContent = () => {
if (isPaid && decryptionPerformed) {
return <MDDisplay className='p-4 rounded-lg w-full' source={lesson.content} />;
}
if (isPaid && !decryptionPerformed) {
return <p className="text-center text-xl text-red-500">This content is paid and needs to be purchased before viewing.</p>;
}
if (lesson?.content) {
return <MDDisplay className='p-4 rounded-lg w-full' source={lesson.content} />;
}
return null;
} }
return ( items.push({
<div className='w-full px-24 pt-12 mx-auto mt-4 max-tab:px-0 max-mob:px-0 max-tab:pt-2 max-mob:pt-2'> label: "Open lesson",
<Toast ref={toastRef} /> icon: "pi pi-arrow-up-right",
<div className='w-full flex flex-row justify-between max-tab:flex-col max-mob:flex-col'> command: () => {
<div className='w-[75vw] mx-auto flex flex-row items-start justify-between max-tab:flex-col max-mob:flex-col max-tab:w-[95vw] max-mob:w-[95vw]'> window.open(`/details/${lesson.id}`, "_blank");
<div className='flex flex-col items-start max-w-[45vw] max-tab:max-w-[100vw] max-mob:max-w-[100vw]'> },
<div className="flex flex-row items-center justify-between w-full"> });
<h1 className='text-4xl'>{lesson?.title}</h1>
<ZapDisplay items.push({
zapAmount={zapAmount} label: "View Nostr note",
event={lesson} icon: "pi pi-globe",
zapsLoading={zapsLoading} command: () => {
/> if (lesson?.d) {
</div> const addr = nip19.naddrEncode({
<div className='pt-2 flex flex-row justify-start w-full mt-2 mb-4'> pubkey: lesson.pubkey,
{lesson && lesson.topics && lesson.topics.length > 0 && ( kind: lesson.kind,
lesson.topics.map((topic, index) => ( identifier: lesson.d,
<Tag className='mr-2 text-white' key={index} value={topic}></Tag> relays: appConfig.defaultRelayUrls || [],
)) });
)} window.open(`https://habla.news/a/${addr}`, "_blank");
</div> }
<div className='text-xl mt-6'>{lesson?.summary && ( },
<div className="text-xl mt-4"> });
{lesson.summary.split('\n').map((line, index) => (
<p key={index}>{line}</p> return items;
))} };
</div>
)} useEffect(() => {
</div> if (!zaps || zapsLoading || zapsError) return;
<div className='flex items-center justify-between w-full mt-8'>
<div className='flex flex-row w-fit items-center'> const total = getTotalFromZaps(zaps, lesson);
<Image
alt="avatar thumbnail" setZapAmount(total);
src={returnImageProxy(lesson.author?.avatar, lesson.author?.pubkey)} }, [zaps, zapsLoading, zapsError, lesson]);
width={50}
height={50} useEffect(() => {
className="rounded-full mr-4" if (isCompleted && !isTracking && setCompleted) {
/> setCompleted(lesson.id);
<p className='text-lg'> }
Created by{' '} }, [isCompleted, isTracking, lesson.id, setCompleted]);
<a rel='noreferrer noopener' target='_blank' className='text-blue-500 hover:underline'>
{lesson.author?.username || lesson.author?.pubkey} useEffect(() => {
</a> if (session?.user?.privkey) {
</p> const privkeyBuffer = Buffer.from(session.user.privkey, "hex");
</div> setNsec(nip19.nsecEncode(privkeyBuffer));
<div className="flex justify-end"> } else if (session?.user?.pubkey) {
<MoreOptionsMenu setNpub(nip19.npubEncode(session.user.pubkey));
menuItems={buildMenuItems()} }
additionalLinks={lesson?.additionalLinks || []} }, [session]);
isMobileView={isMobileView}
/> useEffect(() => {
</div> if (lesson) {
</div> const addr = nip19.naddrEncode({
</div> pubkey: lesson.pubkey,
<div className='flex flex-col max-tab:mt-12 max-mob:mt-12'> kind: lesson.kind,
{lesson && ( identifier: lesson.d,
<div className='flex flex-col items-center justify-between rounded-lg h-72 p-4 bg-gray-700 drop-shadow-md'> relays: appConfig.defaultRelayUrls,
<Image });
alt="course thumbnail" setNAddress(addr);
src={returnImageProxy(lesson.image)} }
width={344} }, [lesson]);
height={194}
className="w-[344px] h-[194px] object-cover object-top rounded-lg" const renderContent = () => {
/> if (isPaid && decryptionPerformed) {
</div> return (
)} <MDDisplay className="p-4 rounded-lg w-full" source={lesson.content} />
</div> );
}
if (isPaid && !decryptionPerformed) {
return (
<p className="text-center text-xl text-red-500">
This content is paid and needs to be purchased before viewing.
</p>
);
}
if (lesson?.content) {
return (
<MDDisplay className="p-4 rounded-lg w-full" source={lesson.content} />
);
}
return null;
};
return (
<div className="w-full px-24 pt-12 mx-auto mt-4 max-tab:px-0 max-mob:px-0 max-tab:pt-2 max-mob:pt-2">
<Toast ref={toastRef} />
<div className="w-full flex flex-row justify-between max-tab:flex-col max-mob:flex-col">
<div className="w-[75vw] mx-auto flex flex-row items-start justify-between max-tab:flex-col max-mob:flex-col max-tab:w-[95vw] max-mob:w-[95vw]">
<div className="flex flex-col items-start max-w-[45vw] max-tab:max-w-[100vw] max-mob:max-w-[100vw]">
<div className="flex flex-row items-center justify-between w-full">
<h1 className="text-4xl">{lesson?.title}</h1>
<ZapDisplay
zapAmount={zapAmount}
event={lesson}
zapsLoading={zapsLoading}
/>
</div>
<div className="pt-2 flex flex-row justify-start w-full mt-2 mb-4">
{lesson &&
lesson.topics &&
lesson.topics.length > 0 &&
lesson.topics.map((topic, index) => (
<Tag
className="mr-2 text-white"
key={index}
value={topic}
></Tag>
))}
</div>
<div className="text-xl mt-6">
{lesson?.summary && (
<div className="text-xl mt-4">
{lesson.summary.split("\n").map((line, index) => (
<p key={index}>{line}</p>
))}
</div> </div>
)}
</div> </div>
<div className='w-[75vw] mx-auto mt-12 p-12 border-t-2 border-gray-300 max-tab:p-0 max-mob:p-0 max-tab:max-w-[100vw] max-mob:max-w-[100vw]'> <div className="flex items-center justify-between w-full mt-8">
{renderContent()} <div className="flex flex-row w-fit items-center">
<Image
alt="avatar thumbnail"
src={returnImageProxy(
lesson.author?.avatar,
lesson.author?.pubkey
)}
width={50}
height={50}
className="rounded-full mr-4"
/>
<p className="text-lg">
Created by{" "}
<a
rel="noreferrer noopener"
target="_blank"
className="text-blue-500 hover:underline"
>
{lesson.author?.username || lesson.author?.pubkey}
</a>
</p>
</div>
<div className="flex justify-end">
<MoreOptionsMenu
menuItems={buildMenuItems()}
additionalLinks={lesson?.additionalLinks || []}
isMobileView={isMobileView}
/>
</div>
</div> </div>
</div>
<div className="flex flex-col max-tab:mt-12 max-mob:mt-12">
{lesson && (
<div className="flex flex-col items-center justify-between rounded-lg h-72 p-4 bg-gray-700 drop-shadow-md">
<Image
alt="course thumbnail"
src={returnImageProxy(lesson.image)}
width={344}
height={194}
className="w-[344px] h-[194px] object-cover object-top rounded-lg"
/>
</div>
)}
</div>
</div> </div>
) </div>
} <div className="w-[75vw] mx-auto mt-12 p-12 border-t-2 border-gray-300 max-tab:p-0 max-mob:p-0 max-tab:max-w-[100vw] max-mob:max-w-[100vw]">
{renderContent()}
</div>
{nAddress !== null &&
(!isPaid || decryptionPerformed || session?.user?.role?.subscribed) && (
<div className="px-4">
{nsec || npub ? (
<ZapThreadsWrapper
anchor={nAddress}
user={nsec || npub || null}
relays={appConfig.defaultRelayUrls.join(",")}
disable="zaps"
/>
) : (
<ZapThreadsWrapper
anchor={nAddress}
user={npub}
relays={appConfig.defaultRelayUrls.join(",")}
disable="zaps"
/>
)}
</div>
)}
</div>
);
};
export default CourseLesson; export default CourseLesson;

View File

@ -9,7 +9,7 @@ const appConfig = {
"wss://purplerelay.com/", "wss://purplerelay.com/",
"wss://relay.devs.tools/" "wss://relay.devs.tools/"
], ],
authorPubkeys: ["f33c8a9617cb15f705fc70cd461cfd6eaf22f9e24c33eabad981648e5ec6f741", "c67cd3e1a83daa56cff16f635db2fdb9ed9619300298d4701a58e68e84098345"], authorPubkeys: ["f33c8a9617cb15f705fc70cd461cfd6eaf22f9e24c33eabad981648e5ec6f741", "c67cd3e1a83daa56cff16f635db2fdb9ed9619300298d4701a58e68e84098345", "b9f4c34dc25b2ddd785c007bf6e12619bb1c9b8335b8d75d37bf76e97d1a0e31"],
customLightningAddresses: [ customLightningAddresses: [
{ {
// todo remove need for lowercase // todo remove need for lowercase