import { json, type RequestEvent } from '@sveltejs/kit'; import { promises } from 'fs'; import prisma from '$lib/prisma'; import { tokenIsAvailable } from '$lib/utils'; /** @type {import('./$types').RequestHandler} */ export async function GET({ params, url } : RequestEvent) { const id = params.id; const filter = url.searchParams.get('filter') || 'new' const search = url.searchParams.get('search') || '' const gallery = await prisma.gallery.findFirst({ where: { id, }, select: { image: true, id: true, prompt: true, createdAt: true, user: { select: { id: true, name: true, sub: true, picture: true, preferred_username: true, } }, comments: { select: { id: true, createdAt: true, text: true, user: { select: { id: true, name: true, sub: true, picture: true, preferred_username: true, } } } }, model: { select: { image: true, id: true, } }, reactions: { select: { id: true, emoji: true, userId: true, user: { select: { id: true, name: true, sub: true, picture: true, preferred_username: true, } } } } } }) if (!gallery) { return json({ error: { token: "Gallery not found" } }, { status: 404 }) } const next = await prisma.gallery.findFirst({ where: { isPublic: true, createdAt: { lt: gallery.createdAt }, OR: [ { prompt: { contains: search } }, ], }, orderBy: { ...(filter === 'new' ? { createdAt: 'desc' } : { reactions: { _count: 'desc' } } ) }, select: { id: true, } }) const previous = await prisma.gallery.findFirst({ where: { isPublic: true, createdAt: { gt: gallery.createdAt }, OR: [ { prompt: { contains: search } }, ], }, orderBy: { ...(filter === 'new' ? { createdAt: 'desc' } : { reactions: { _count: 'desc' } } ) }, select: { id: true, } }) return json({ gallery, next: next ? next.id : undefined, previous: previous ? previous.id : undefined, }) } export async function DELETE({ params, cookies }: RequestEvent) { const id = params.id; const token = cookies.get('hf_access_token') if (!token) { return json({ error: "You must be logged" }, { status: 401 }) } const user = await tokenIsAvailable(token) if (!user) { return json({ error: "Invalid token" }, { status: 401 }) } const gallery = await prisma.gallery.findFirst({ where: { id } }) if (gallery?.userId !== user.sub && !process?.env?.SECRET_HF_ADMIN?.includes(user?.sub)) { return json({ error: "You are not authorized to delete this gallery" }, { status: 401 }) } if (!gallery) { return json({ error: "Gallery not found" }, { status: 404 }) } await prisma.gallery.delete({ where: { id } }) await promises.unlink(`${process.env.PUBLIC_FILE_UPLOAD_DIR}/${gallery?.image}`) return json({ success: true }) }