76 lines
2.7 KiB
TypeScript
76 lines
2.7 KiB
TypeScript
"use server";
|
|
|
|
import { revalidatePath } from "next/cache";
|
|
import { mkdir, writeFile } from "fs/promises";
|
|
import path from "path";
|
|
import { prisma } from "@/lib/prisma";
|
|
import { siteSettings } from "@/lib/services/site-settings";
|
|
|
|
const MEDIA_DIR = "public/assets/images/media/logo";
|
|
|
|
export async function saveLogo(formData: FormData): Promise<{ success: boolean; url?: string; error?: string }> {
|
|
try {
|
|
const file = formData.get("file") as File | null;
|
|
if (!file) return { success: false, error: "No file provided" };
|
|
|
|
const mimeExt: Record<string, string> = { "image/png": "png", "image/gif": "gif", "image/jpeg": "jpg", "image/webp": "webp" };
|
|
const ext = mimeExt[file.type] ?? "png";
|
|
const filename = `logo-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
|
|
const dir = path.join(process.cwd(), MEDIA_DIR);
|
|
const filePath = path.join(dir, filename);
|
|
|
|
const buffer = Buffer.from(await file.arrayBuffer());
|
|
await mkdir(dir, { recursive: true });
|
|
await writeFile(filePath, buffer);
|
|
|
|
const url = `/api/media/logo/${filename}`;
|
|
|
|
await prisma.websiteSetting.upsert({
|
|
where: { key: "cms_logo" },
|
|
update: { value: url },
|
|
create: { key: "cms_logo", value: url, comment: "Logo (generator)" },
|
|
});
|
|
|
|
siteSettings.reload();
|
|
revalidatePath("/", "layout");
|
|
|
|
return { success: true, url };
|
|
} catch (e) {
|
|
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
|
}
|
|
}
|
|
|
|
export async function saveLogoFromUrl(gifUrl: string): Promise<{ success: boolean; url?: string; error?: string }> {
|
|
try {
|
|
const res = await fetch(gifUrl);
|
|
if (!res.ok) return { success: false, error: `Failed to fetch GIF: ${res.status}` };
|
|
|
|
const contentType = res.headers.get("content-type") ?? "image/gif";
|
|
const buffer = Buffer.from(await res.arrayBuffer());
|
|
|
|
const mimeExt: Record<string, string> = { "image/png": "png", "image/gif": "gif", "image/jpeg": "jpg", "image/webp": "webp" };
|
|
const ext = mimeExt[contentType] ?? "gif";
|
|
const filename = `logo-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
|
|
const dir = path.join(process.cwd(), MEDIA_DIR);
|
|
const filePath = path.join(dir, filename);
|
|
|
|
await mkdir(dir, { recursive: true });
|
|
await writeFile(filePath, buffer);
|
|
|
|
const url = `/api/media/logo/${filename}`;
|
|
|
|
await prisma.websiteSetting.upsert({
|
|
where: { key: "cms_logo" },
|
|
update: { value: url },
|
|
create: { key: "cms_logo", value: url, comment: "Logo (generator)" },
|
|
});
|
|
|
|
siteSettings.reload();
|
|
revalidatePath("/", "layout");
|
|
|
|
return { success: true, url };
|
|
} catch (e) {
|
|
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
|
}
|
|
}
|