From 187573088bef8e3911b74c0112aca143cfca3657 Mon Sep 17 00:00:00 2001 From: austinkelsay Date: Mon, 25 Mar 2024 10:23:42 -0500 Subject: [PATCH] Form improvements --- src/components/forms/CourseForm.js | 10 +- src/components/forms/ResourceForm.js | 10 +- src/components/forms/WorkshopForm.js | 174 ++++++++++++++++++++++++++- 3 files changed, 189 insertions(+), 5 deletions(-) diff --git a/src/components/forms/CourseForm.js b/src/components/forms/CourseForm.js index fa8a000..517f06a 100644 --- a/src/components/forms/CourseForm.js +++ b/src/components/forms/CourseForm.js @@ -2,8 +2,9 @@ import React, { useState } from "react"; import { InputText } from "primereact/inputtext"; import { InputNumber } from "primereact/inputnumber"; import { InputSwitch } from "primereact/inputswitch"; -import { Editor } from "primereact/editor"; +import { useToast } from "@/hooks/useToast"; import { Button } from "primereact/button"; +import { v4 as uuidv4 } from 'uuid'; import 'primeicons/primeicons.css'; const CourseForm = () => { @@ -13,8 +14,11 @@ const CourseForm = () => { const [price, setPrice] = useState(0); const [text, setText] = useState(''); const [resources, setResources] = useState(['']); + const [coverImage, setCoverImage] = useState(''); const [topics, setTopics] = useState(['']); + const showToast = useToast(); + const handleSubmit = (e) => { e.preventDefault(); const payload = { @@ -26,6 +30,7 @@ const CourseForm = () => { topics: topics.map(topic => topic.trim().toLowerCase()), resources: resources.map(resource => resource.trim()) }; + console.log(payload); } @@ -65,6 +70,9 @@ const CourseForm = () => {
setSummary(e.target.value)} placeholder="Summary" />
+
+ setCoverImage(e.target.value)} placeholder="Cover Image URL" /> +

Paid Course

diff --git a/src/components/forms/ResourceForm.js b/src/components/forms/ResourceForm.js index e47bc44..2fb5e26 100644 --- a/src/components/forms/ResourceForm.js +++ b/src/components/forms/ResourceForm.js @@ -19,7 +19,8 @@ const ResourceForm = () => { const [checked, setChecked] = useState(false); const [price, setPrice] = useState(0); const [text, setText] = useState(''); - const [topics, setTopics] = useState(['']); // Initialize with an empty string to show one input by default + const [coverImage, setCoverImage] = useState(''); + const [topics, setTopics] = useState(['']); const [user] = useLocalStorageWithEffect('user', {}); @@ -28,14 +29,14 @@ const ResourceForm = () => { const { publishAll } = useNostr(); const handleSubmit = (e) => { - e.preventDefault(); // Prevents the default form submission mechanism + e.preventDefault(); const payload = { title, summary, isPaidResource: checked, price: checked ? price : null, content: text, - topics: topics.map(topic => topic.trim().toLowerCase()) // Process topics as they are + topics: topics.map(topic => topic.trim().toLowerCase()) }; if (checked) { @@ -245,6 +246,9 @@ const ResourceForm = () => {
setSummary(e.target.value)} placeholder="Summary" />
+
+ setCoverImage(e.target.value)} placeholder="Cover Image URL" /> +

Paid Resource

diff --git a/src/components/forms/WorkshopForm.js b/src/components/forms/WorkshopForm.js index 70d25c6..8ee11e2 100644 --- a/src/components/forms/WorkshopForm.js +++ b/src/components/forms/WorkshopForm.js @@ -1,8 +1,15 @@ import React, { useState } from 'react'; +import axios from 'axios'; import { InputText } from 'primereact/inputtext'; import { InputNumber } from 'primereact/inputnumber'; import { InputSwitch } from 'primereact/inputswitch'; +import { FileUpload } from 'primereact/fileupload'; +import { verifyEvent, nip19 } from "nostr-tools" +import { useNostr } from '@/hooks/useNostr'; import { Button } from 'primereact/button'; +import { v4 as uuidv4 } from 'uuid'; +import { useToast } from '@/hooks/useToast'; +import { useLocalStorageWithEffect } from '@/hooks/useLocalStorage'; import 'primeicons/primeicons.css'; const WorkshopForm = () => { @@ -11,8 +18,15 @@ const WorkshopForm = () => { const [checked, setChecked] = useState(false); const [price, setPrice] = useState(0); const [videoUrl, setVideoUrl] = useState(''); + const [coverImage, setCoverImage] = useState(''); const [topics, setTopics] = useState(['']); + const [user] = useLocalStorageWithEffect('user', {}); + + const { showToast } = useToast(); + + const { publishAll } = useNostr(); + const handleSubmit = (e) => { e.preventDefault(); let embedCode = ''; @@ -34,12 +48,167 @@ const WorkshopForm = () => { summary, isPaidResource: checked, price: checked ? price : null, - videoUrl, + embedCode, topics: topics.map(topic => topic.trim().toLowerCase()) // Include topics in the payload }; console.log(payload); + + if (checked) { + broadcastPaidWorkshop(payload); + } else { + broadcastFreeWorkshop(payload); + } }; + const broadcastFreeWorkshop = async (payload) => { + const newWorkshopId = uuidv4(); + const event = { + kind: 30023, + content: payload.embedCode, + created_at: Math.floor(Date.now() / 1000), + tags: [ + ['d', newWorkshopId], + ['title', payload.title], + ['summary', payload.summary], + ['image', ''], + ['t', ...topics], + ['published_at', Math.floor(Date.now() / 1000).toString()], + ] + }; + + const signedEvent = await window.nostr.signEvent(event); + + const eventVerification = await verifyEvent(signedEvent); + + if (!eventVerification) { + showToast('error', 'Error', 'Event verification failed. Please try again.'); + return; + } + + const nAddress = nip19.naddrEncode({ + pubkey: signedEvent.pubkey, + kind: signedEvent.kind, + identifier: newWorkshopId, + }) + + console.log('nAddress:', nAddress); + + const userResponse = await axios.get(`/api/users/${user.pubkey}`) + + if (!userResponse.data) { + showToast('error', 'Error', 'User not found', 'Please try again.'); + return; + } + + const resourcePayload = { + id: newWorkshopId, + userId: userResponse.data.id, + price: 0, + noteId: nAddress, + } + const response = await axios.post(`/api/resources`, resourcePayload); + + console.log('response:', response); + + if (response.status !== 201) { + showToast('error', 'Error', 'Failed to create resource. Please try again.'); + return; + } + + const publishResponse = await publishAll(signedEvent); + + if (!publishResponse) { + showToast('error', 'Error', 'Failed to publish resource. Please try again.'); + return; + } else if (publishResponse?.failedRelays) { + publishResponse?.failedRelays.map(relay => { + showToast('warn', 'Warning', `Failed to publish to relay: ${relay}`); + }); + } + + publishResponse?.successfulRelays.map(relay => { + showToast('success', 'Success', `Published to relay: ${relay}`); + }) + } + + // For images, whether included in the markdown content or not, clients SHOULD use image tags as described in NIP-58. This allows clients to display images in carousel format more easily. + const broadcastPaidWorkshop = async (payload) => { + // encrypt the content with NEXT_PUBLIC_APP_PRIV_KEY to NEXT_PUBLIC_APP_PUBLIC_KEY + const encryptedContent = await nip04.encrypt(process.env.NEXT_PUBLIC_APP_PRIV_KEY ,process.env.NEXT_PUBLIC_APP_PUBLIC_KEY, payload.content); + const newWorkshopId = uuidv4(); + const event = { + kind: 30402, + content: encryptedContent, + created_at: Math.floor(Date.now() / 1000), + tags: [ + ['title', payload.title], + ['summary', payload.summary], + ['t', ...topics], + ['image', ''], + ['d', newresourceId], + ['location', `https://plebdevs.com/resource/${newWorkshopId}`], + ['published_at', Math.floor(Date.now() / 1000).toString()], + ['price', payload.price] + ] + }; + + const signedEvent = await window.nostr.signEvent(event); + + const eventVerification = await verifyEvent(signedEvent); + + if (!eventVerification) { + showToast('error', 'Error', 'Event verification failed. Please try again.'); + return; + } + + const nAddress = nip19.naddrEncode({ + pubkey: signedEvent.pubkey, + kind: signedEvent.kind, + identifier: newWorkshopId, + }) + + console.log('nAddress:', nAddress); + + const userResponse = await axios.get(`/api/users/${user.pubkey}`) + + if (!userResponse.data) { + showToast('error', 'Error', 'User not found', 'Please try again.'); + return; + } + + const resourcePayload = { + id: newWorkshopId, + userId: userResponse.data.id, + price: payload.price || 0, + noteId: nAddress, + } + const response = await axios.post(`/api/resources`, resourcePayload); + + if (response.status !== 201) { + showToast('error', 'Error', 'Failed to create resource. Please try again.'); + return; + } + + const publishResponse = await publishAll(signedEvent); + + if (!publishResponse) { + showToast('error', 'Error', 'Failed to publish resource. Please try again.'); + return; + } else if (publishResponse?.failedRelays) { + publishResponse?.failedRelays.map(relay => { + showToast('warn', 'Warning', `Failed to publish to relay: ${relay}`); + }); + } + + publishResponse?.successfulRelays.map(relay => { + showToast('success', 'Success', `Published to relay: ${relay}`); + }) + } + + const onUpload = (event) => { + showToast('success', 'Success', 'File Uploaded'); + console.log(event.files[0]); + } const handleTopicChange = (index, value) => { const updatedTopics = topics.map((topic, i) => i === index ? value : topic); @@ -78,6 +247,9 @@ const WorkshopForm = () => {
setVideoUrl(e.target.value)} placeholder="Video URL" />
+
+ setCoverImage(e.target.value)} placeholder="Cover Image URL" /> +
{topics.map((topic, index) => (