cleanup upload-component pt1

This commit is contained in:
2025-04-13 13:28:57 +02:00
parent 4580a52b73
commit 035089232a

View File

@@ -1,6 +1,6 @@
"use client" "use client"
import { useState, useEffect, useCallback, type ChangeEvent, type FormEvent } from "react" import { useState, type ChangeEvent, type FormEvent } from "react"
import { ReloadIcon } from "@radix-ui/react-icons" import { ReloadIcon } from "@radix-ui/react-icons"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
@@ -255,69 +255,15 @@ async function calculateBlurhash(file: File): Promise<string> {
}) })
} }
async function calculateSHA256(file: File): Promise<string> {
// In a browser environment, we'd use the Web Crypto API
// This is a simplified mock implementation
return new Promise((resolve) => {
setTimeout(() => {
// Generate a random SHA256-like hash for demo purposes
const mockHash = Array.from({ length: 64 }, () => "0123456789abcdef"[Math.floor(Math.random() * 16)]).join("")
resolve(mockHash)
}, 500)
})
}
const UploadComponent = () => { const UploadComponent = () => {
const { createHash } = require("crypto") const { createHash } = require("crypto")
const loginType = typeof window !== "undefined" ? window.localStorage.getItem("loginType") : null const loginType = typeof window !== "undefined" ? window.localStorage.getItem("loginType") : null
const [previewUrl, setPreviewUrl] = useState("") const [previewUrl, setPreviewUrl] = useState("")
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const [uploadedNoteId, setUploadedNoteId] = useState("")
const [retryCount, setRetryCount] = useState(0)
const [shouldFetch, setShouldFetch] = useState(false)
const [serverChoice, setServerChoice] = useState("blossom.band") const [serverChoice, setServerChoice] = useState("blossom.band")
const [events, setEvents] = useState<any[]>([])
const [isNoteLoading, setIsNoteLoading] = useState(false)
const [uploadResponse, setUploadResponse] = useState<UploadResponse | null>(null) const [uploadResponse, setUploadResponse] = useState<UploadResponse | null>(null)
const [showUploadForm, setShowUploadForm] = useState(true) const [showUploadForm, setShowUploadForm] = useState(true)
useEffect(() => {
if (uploadedNoteId) {
setShouldFetch(true)
}
}, [uploadedNoteId])
useEffect(() => {
let timeoutId: NodeJS.Timeout
if (shouldFetch && events.length === 0 && !isNoteLoading) {
setIsNoteLoading(true)
// Simulate fetching events
timeoutId = setTimeout(() => {
setIsNoteLoading(false)
// After a few retries, simulate finding the event
if (retryCount >= 2) {
setEvents([{ id: uploadedNoteId }])
} else {
setRetryCount((prevCount) => prevCount + 1)
}
}, 2000)
}
return () => {
if (timeoutId) {
clearTimeout(timeoutId)
}
}
}, [shouldFetch, events, isNoteLoading, retryCount, uploadedNoteId])
const handleRetry = useCallback(() => {
setRetryCount((prevCount) => prevCount + 1)
setShouldFetch(false)
setTimeout(() => setShouldFetch(true), 100)
}, [])
const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => { const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0] const file = event.target.files?.[0]
if (file) { if (file) {
@@ -336,10 +282,6 @@ const UploadComponent = () => {
setUploadResponse(null) setUploadResponse(null)
setShowUploadForm(true) setShowUploadForm(true)
setPreviewUrl("") setPreviewUrl("")
setUploadedNoteId("")
setEvents([])
setRetryCount(0)
setShouldFetch(false)
} }
async function onSubmit(event: FormEvent<HTMLFormElement>) { async function onSubmit(event: FormEvent<HTMLFormElement>) {
@@ -347,15 +289,13 @@ const UploadComponent = () => {
setIsLoading(true) setIsLoading(true)
const formData = new FormData(event.currentTarget) const formData = new FormData(event.currentTarget)
const desc = formData.get("description") as string
const file = formData.get("file") as File const file = formData.get("file") as File
let sha256 = "" let sha256 = ""
let finalNoteContent = desc
let finalFileUrl = "" let finalFileUrl = ""
console.log("File:", file) console.log("File:", file)
if (!desc && !file.size) { if (!file.size) {
alert("Please enter a description and/or upload a file") alert("Please select a file first")
setIsLoading(false) setIsLoading(false)
return return
} }
@@ -379,7 +319,6 @@ const UploadComponent = () => {
const unixNow = () => Math.floor(Date.now() / 1000) const unixNow = () => Math.floor(Date.now() / 1000)
const newExpirationValue = () => (unixNow() + 60 * 5).toString() const newExpirationValue = () => (unixNow() + 60 * 5).toString()
const pubkey = window.localStorage.getItem("pubkey")
const createdAt = Math.floor(Date.now() / 1000) const createdAt = Math.floor(Date.now() / 1000)
// Create auth event for blossom auth via nostr // Create auth event for blossom auth via nostr
@@ -420,15 +359,6 @@ const UploadComponent = () => {
// Set the upload response data // Set the upload response data
setUploadResponse(responseJson) setUploadResponse(responseJson)
let blurhash = ""
if (file && file.type.startsWith("image/")) {
try {
blurhash = await calculateBlurhash(file)
} catch (error) {
console.error("Error calculating blurhash:", error)
}
}
if (finalFileUrl) { if (finalFileUrl) {
const image = new Image() const image = new Image()
image.src = URL.createObjectURL(file) image.src = URL.createObjectURL(file)
@@ -436,14 +366,11 @@ const UploadComponent = () => {
image.onload = resolve image.onload = resolve
}) })
finalNoteContent = desc
} }
setIsLoading(false) setIsLoading(false)
if (finalFileUrl != null) { if (finalFileUrl != null) {
setShowUploadForm(false) setShowUploadForm(false)
setShouldFetch(true)
setRetryCount(0)
} }
} else { } else {
throw new Error("Failed to upload file: " + (await res.text())) throw new Error("Failed to upload file: " + (await res.text()))