import { json, type RequestEvent } from '@sveltejs/kit'; import prisma from '$lib/prisma'; import { tokenIsAvailable } from '$lib/utils'; /** @type {import('./$types').RequestHandler} */ export async function GET(request : RequestEvent) { const token = request.cookies.get('hf_access_token') let IS_ADMIN = !!token if (token) { const user = await tokenIsAvailable(token) if (user) { IS_ADMIN = process?.env?.SECRET_HF_ADMIN ? process?.env?.SECRET_HF_ADMIN.includes(user.sub) : false } } const page = parseInt(request.url.searchParams.get('page') || '0') const filter = request.url.searchParams.get('filter') || 'hotest' const search = request.url.searchParams.get('search') || '' const limit = parseInt(request.url.searchParams.get('limit') || '20') const cards = await prisma.model.findMany({ where: { ...(IS_ADMIN ? {} : { isPublic: true }), OR: [ { id: { contains: search } }, ] }, orderBy: { ...(filter === 'hotest' ? { downloads: 'desc' } : filter === 'likes' ? { likes: 'desc' } : { createdAt: 'desc' }) }, skip: page * limit, take: limit, }) const total_reposId = await prisma.model.count({ where: { ...(IS_ADMIN ? {} : { isPublic: true }), OR: [ { id: { contains: search } }, ] }, }) return json({ cards, total_items: total_reposId }) } export async function PATCH({ request } : RequestEvent) { const headers = Object.fromEntries(request.headers.entries()); if (headers["x-hf-token"] !== process.env.SECRET_HF_TOKEN) { return Response.json({ message: "Wrong castle fam :^)" }, { status: 401 }); } const models = await prisma.model.findMany({ where: { isPublic: true, } }) let total_updates = 0; for (const model of models) { const response = await fetch(`https://huggingface.co/api/models/${model.id}`) const hf_model = await response.json(); await prisma.model.update({ where: { id: model.id }, data: { likes: hf_model.likes, downloads: hf_model.downloads, } }) total_updates++ } return json({ message: `Updated ${total_updates} models` }) }