26 lines
1.5 KiB
TypeScript
26 lines
1.5 KiB
TypeScript
import { cookies } from "next/headers";
|
|
import { promises as fs } from "node:fs";
|
|
import path from "node:path";
|
|
import { NextResponse } from "next/server";
|
|
import { COOKIE_NAME, validAdminToken } from "@/lib/admin-auth";
|
|
|
|
export const dynamic = "force-dynamic";
|
|
export async function GET() {
|
|
if (!validAdminToken(cookies().get(COOKIE_NAME)?.value)) return NextResponse.json({ error: "انتهت الجلسة، سجّل الدخول مجدداً" }, { status: 401 });
|
|
const files: { url: string; name: string; type: "image" | "pdf" }[] = [];
|
|
async function walk(relative: string) {
|
|
let entries;
|
|
try { entries = await fs.readdir(path.join(process.cwd(), "public", relative), { withFileTypes: true }); }
|
|
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return; throw error; }
|
|
for (const entry of entries) {
|
|
const next = `${relative}/${entry.name}`;
|
|
if (entry.isDirectory()) await walk(next);
|
|
else if (entry.isFile() && /\.(png|jpe?g|webp|avif|svg|pdf)$/i.test(entry.name)) files.push({ url: `/${next}`, name: entry.name, type: /\.pdf$/i.test(entry.name) ? "pdf" : "image" });
|
|
}
|
|
}
|
|
try {
|
|
await Promise.all([walk("uploads"), walk("images"), walk("documents")]);
|
|
return NextResponse.json({ files: files.sort((a,b)=>b.name.localeCompare(a.name)) }, { headers: { "Cache-Control": "no-store" } });
|
|
} catch { return NextResponse.json({ error: "تعذّرت قراءة مكتبة الملفات" }, { status: 500 }); }
|
|
}
|