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 committed by austinkelsay
parent 34680d244f
commit 62441e01a0
No known key found for this signature in database
GPG Key ID: 5A763922E5BA08EE
4 changed files with 277 additions and 73 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
const zapRef = useRef(null);
useEffect(() => {
// Only load the script if the user is authorized
if (!isAuthorized) {
return;
}
// 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
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
script.async = true;
// Function to handle the script load event
const handleScriptLoad = () => {
// Create a new <zap-threads> element
const zapElement = document.createElement('zap-threads');
zapElement.setAttribute('anchor', anchor);
if (user) zapElement.setAttribute('user', user);
zapElement.setAttribute('relays', relays.replace(/\s/g, ''));
if (disable) zapElement.setAttribute('disable', disable);
const zapElement = document.createElement("zap-threads");
zapElement.setAttribute("anchor", anchor);
// Remove any existing <zap-threads> element before appending a new one
if (zapRef.current && zapRef.current.firstChild) {
zapRef.current.removeChild(zapRef.current.firstChild);
// Only set user if it exists and is not null
if (user) {
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) {
zapRef.current.appendChild(zapElement);
}
};
// 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
document.body.appendChild(script);
// Cleanup function to remove the <zap-threads> element and the <script> element when the component is unmounted
return () => {
// Remove the <zap-threads> element from the <div> referenced by zapRef
if (zapRef.current && zapRef.current.firstChild) {
zapRef.current.removeChild(zapRef.current.firstChild);
if (zapRef.current) {
while (zapRef.current.firstChild) {
zapRef.current.removeChild(zapRef.current.firstChild);
}
}
// Remove the <script> element from the <body> of the document
document.body.removeChild(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
return <div className={`overflow-x-hidden ${className || ''}`} ref={zapRef} />;
return (
<div className={`overflow-x-hidden ${className || ""}`} ref={zapRef} />
);
};
export default ZapThreadsWrapper;

View File

@ -22,16 +22,31 @@ import useWindowWidth from '@/hooks/useWindowWidth';
import GenericButton from '@/components/buttons/GenericButton';
import appConfig from '@/config/appConfig';
import { BookOpen } from 'lucide-react';
import ZapThreadsWrapper from '@/components/ZapThreadsWrapper';
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 [lessonCount, setLessonCount] = useState(0);
const [nAddress, setNAddress] = useState(null);
const [npub, setNpub] = useState(null);
const [nsec, setNsec] = useState(null);
const router = useRouter();
const { returnImageProxy } = useImageProxy();
const windowWidth = useWindowWidth();
const isMobile = windowWidth < 768;
const { data: session } = useSession();
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]);
useEffect(() => {
if (zaps.length > 0) {
@ -97,7 +112,9 @@ export function CourseTemplate({ course, showMetaTags = true }) {
</div>
<CardHeader className="flex flex-row justify-between items-center p-4 border-b border-gray-700">
<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 className="text-[#f8f8ff]">
<ZapDisplay
@ -173,6 +190,31 @@ export function CourseTemplate({ course, showMetaTags = true }) {
className="items-center py-2"
/>
</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>
);
}

View File

@ -120,11 +120,24 @@ export default function CourseDetails({
}
}, [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) {
if (
session?.user &&
session.user?.role?.subscribed &&
decryptionPerformed
) {
return (
<GenericButton
tooltipOptions={{ position: 'top' }}
tooltipOptions={{ position: "top" }}
tooltip={`You are subscribed so you can access all paid content`}
icon="pi pi-check"
label="Subscribed"
@ -268,6 +281,40 @@ export default function CourseDetails({
</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

@ -1,26 +1,39 @@
import React, { useEffect, useState, useRef } from 'react';
import { Tag } from 'primereact/tag';
import Image from 'next/image';
import { useImageProxy } from '@/hooks/useImageProxy';
import { getTotalFromZaps } from '@/utils/lightning';
import ZapDisplay from '@/components/zaps/ZapDisplay';
import dynamic from 'next/dynamic';
import { useZapsQuery } from '@/hooks/nostrQueries/zaps/useZapsQuery';
import { Toast } from 'primereact/toast';
import useTrackDocumentLesson from '@/hooks/tracking/useTrackDocumentLesson';
import useWindowWidth from '@/hooks/useWindowWidth';
import { nip19 } from 'nostr-tools';
import appConfig from '@/config/appConfig';
import MoreOptionsMenu from '@/components/ui/MoreOptionsMenu';
import { useSession } from 'next-auth/react';
import React, { useEffect, useState, useRef } from "react";
import { Tag } from "primereact/tag";
import Image from "next/image";
import { useImageProxy } from "@/hooks/useImageProxy";
import { getTotalFromZaps } from "@/utils/lightning";
import ZapDisplay from "@/components/zaps/ZapDisplay";
import dynamic from "next/dynamic";
import { useZapsQuery } from "@/hooks/nostrQueries/zaps/useZapsQuery";
import { Toast } from "primereact/toast";
import useTrackDocumentLesson from "@/hooks/tracking/useTrackDocumentLesson";
import useWindowWidth from "@/hooks/useWindowWidth";
import { nip19 } from "nostr-tools";
import appConfig from "@/config/appConfig";
import MoreOptionsMenu from "@/components/ui/MoreOptionsMenu";
import { useSession } from "next-auth/react";
import ZapThreadsWrapper from "@/components/ZapThreadsWrapper";
const MDDisplay = dynamic(() => import('@uiw/react-markdown-preview'), {
const MDDisplay = dynamic(() => import("@uiw/react-markdown-preview"), {
ssr: false,
});
const CourseLesson = ({ lesson, course, decryptionPerformed, isPaid, setCompleted }) => {
const CourseLesson = ({
lesson,
course,
decryptionPerformed,
isPaid,
setCompleted,
}) => {
const [zapAmount, setZapAmount] = useState(0);
const { zaps, zapsLoading, zapsError } = useZapsQuery({ event: lesson, type: 'lesson' });
const [nAddress, setNAddress] = useState(null);
const [nsec, setNsec] = useState(null);
const [npub, setNpub] = useState(null);
const { zaps, zapsLoading, zapsError } = useZapsQuery({
event: lesson,
type: "lesson",
});
const { returnImageProxy } = useImageProxy();
const menuRef = useRef(null);
const toastRef = useRef(null);
@ -28,42 +41,46 @@ const CourseLesson = ({ lesson, course, decryptionPerformed, isPaid, setComplete
const isMobileView = windowWidth <= 768;
const { data: session } = useSession();
const readTime = lesson?.content ? Math.max(30, Math.ceil(lesson.content.length / 20)) : 60;
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 { isCompleted, isTracking, markLessonAsCompleted } =
useTrackDocumentLesson({
lessonId: lesson?.d,
courseId: course?.d,
readTime,
paidCourse: isPaid,
decryptionPerformed,
});
const buildMenuItems = () => {
const items = [];
const hasAccess =
session?.user && (!isPaid || decryptionPerformed || session.user.role?.subscribed);
session?.user &&
(!isPaid || decryptionPerformed || session.user.role?.subscribed);
if (hasAccess) {
items.push({
label: 'Mark as completed',
icon: 'pi pi-check-circle',
label: "Mark as completed",
icon: "pi pi-check-circle",
command: async () => {
try {
await markLessonAsCompleted();
setCompleted && setCompleted(lesson.id);
toastRef.current.show({
severity: 'success',
summary: 'Success',
detail: 'Lesson marked as completed',
severity: "success",
summary: "Success",
detail: "Lesson marked as completed",
life: 3000,
});
} catch (error) {
console.error('Failed to mark lesson as completed:', error);
console.error("Failed to mark lesson as completed:", error);
toastRef.current.show({
severity: 'error',
summary: 'Error',
detail: 'Failed to mark lesson as completed',
severity: "error",
summary: "Error",
detail: "Failed to mark lesson as completed",
life: 3000,
});
}
@ -72,16 +89,16 @@ const CourseLesson = ({ lesson, course, decryptionPerformed, isPaid, setComplete
}
items.push({
label: 'Open lesson',
icon: 'pi pi-arrow-up-right',
label: "Open lesson",
icon: "pi pi-arrow-up-right",
command: () => {
window.open(`/details/${lesson.id}`, '_blank');
window.open(`/details/${lesson.id}`, "_blank");
},
});
items.push({
label: 'View Nostr note',
icon: 'pi pi-globe',
label: "View Nostr note",
icon: "pi pi-globe",
command: () => {
if (lesson?.d) {
const addr = nip19.naddrEncode({
@ -90,7 +107,7 @@ const CourseLesson = ({ lesson, course, decryptionPerformed, isPaid, setComplete
identifier: lesson.d,
relays: appConfig.defaultRelayUrls || [],
});
window.open(`https://habla.news/a/${addr}`, '_blank');
window.open(`https://habla.news/a/${addr}`, "_blank");
}
},
});
@ -112,9 +129,32 @@ const CourseLesson = ({ lesson, course, decryptionPerformed, isPaid, setComplete
}
}, [isCompleted, isTracking, lesson.id, setCompleted]);
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]);
useEffect(() => {
if (lesson) {
const addr = nip19.naddrEncode({
pubkey: lesson.pubkey,
kind: lesson.kind,
identifier: lesson.d,
relays: appConfig.defaultRelayUrls,
});
setNAddress(addr);
}
}, [lesson]);
const renderContent = () => {
if (isPaid && decryptionPerformed) {
return <MDDisplay className="p-4 rounded-lg w-full" source={lesson.content} />;
return (
<MDDisplay className="p-4 rounded-lg w-full" source={lesson.content} />
);
}
if (isPaid && !decryptionPerformed) {
return (
@ -124,7 +164,9 @@ const CourseLesson = ({ lesson, course, decryptionPerformed, isPaid, setComplete
);
}
if (lesson?.content) {
return <MDDisplay className="p-4 rounded-lg w-full" source={lesson.content} />;
return (
<MDDisplay className="p-4 rounded-lg w-full" source={lesson.content} />
);
}
return null;
};
@ -137,20 +179,28 @@ const CourseLesson = ({ lesson, course, decryptionPerformed, isPaid, setComplete
<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} />
<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>
<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) => (
{lesson.summary.split("\n").map((line, index) => (
<p key={index}>{line}</p>
))}
</div>
@ -160,13 +210,16 @@ const CourseLesson = ({ lesson, course, decryptionPerformed, isPaid, setComplete
<div className="flex flex-row w-fit items-center">
<Image
alt="avatar thumbnail"
src={returnImageProxy(lesson.author?.avatar, lesson.author?.pubkey)}
src={returnImageProxy(
lesson.author?.avatar,
lesson.author?.pubkey
)}
width={50}
height={50}
className="rounded-full mr-4"
/>
<p className="text-lg">
Created by{' '}
Created by{" "}
<a
rel="noreferrer noopener"
target="_blank"
@ -203,6 +256,26 @@ const CourseLesson = ({ lesson, course, decryptionPerformed, isPaid, setComplete
<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>
);
};