feat(admin): อัปโหลดรูปโรงหนังจากเครื่อง (เดิมใส่ได้แค่ URL)

- POST /api/admin/uploads (multipart, ≤8MB, ตรวจ magic bytes JPEG/PNG/WebP/AVIF)
  เก็บ data/uploads/cinemas/ คืน /uploads/cinemas/<slug>-<random>-<ts>.<ext>
- GET /uploads/** เสิร์ฟไฟล์อัปโหลด (Nitro route, immutable cache, กัน path traversal)
- PhotosEditor: ปุ่มอัปโหลด + ลากไฟล์มาวาง + Ctrl+V วางจากคลิปบอร์ด, หลายไฟล์พร้อมกัน
- app/lib/upload.ts กติกากลาง + upload.spec.ts (13 tests)
- docs: api.md, admin-guide.md (วิธีอัปโหลด), DESIGN.md, README
This commit is contained in:
Bkk1234 committed 2026-11-15 23:36:35 +07:00
1 parent 251932e548
commit 2c5918a614
10 files changed
+483 -22

No files matched your search

+139 -15
View File
@@ -1,31 +1,121 @@
import { IconPlus, IconTrash } from "@tabler/icons-react";
import { IconPhotoUp, IconPlus, IconTrash } from "@tabler/icons-react";
import { useRef, useState } from "react";
import { MAX_UPLOAD_BYTES } from "@/lib/upload";
/**
* แก้รายการรูปโรงหนัง (อาร์เรย์ `photos`) — ใส่เป็น URL หรือ path ในโปรเจกต์
* รูปแรกใช้เป็นภาพหลักของแกลเลอรี · ลากสลับลำดับไม่ได้ ใช้ปุ่ม ↑/↓ แทน
* แก้รายการรูปโรงหนัง (อาร์เรย์ `photos`)
*
* รองรับ 3 ทาง:
* 1) อัปโหลดไฟล์จากเครื่อง (ปุ่ม / ลากมาวาง / Ctrl+V) → เก็บที่ data/uploads/cinemas
* 2) วางลิงก์หรือพาธเอง (`/images/cinemas/x.webp` หรือ URL ภายนอก)
* 3) สลับลำดับด้วย ↑/↓ · รูปแรก = ภาพหลักของแกลเลอรี
*/
type Props = {
photos: string[];
onChange: (next: string[]) => void;
inputClass: string;
labelClass: string;
/** slug ของโรงที่กำลังแก้ — ใช้ตั้งชื่อไฟล์อัปโหลด */
cinemaSlug?: string;
};
const smallButtonClass =
"flex min-h-9 items-center gap-1 rounded-lg border border-[#303030] px-2 text-xs text-[#999] transition hover:border-[#A92626] hover:text-[#D47272]";
"flex min-h-9 items-center gap-1 rounded-lg border border-[#303030] px-2 text-xs text-[#999] transition hover:border-[#A92626] hover:text-[#D47272] disabled:opacity-50";
const uploadButtonClass =
"flex min-h-10 w-fit items-center gap-2 rounded-lg border border-[#A92626]/60 bg-[#1B1B1B] px-3 text-sm text-white transition hover:border-[#A92626] hover:text-[#D47272] disabled:opacity-50";
export function PhotosEditor({
photos,
onChange,
inputClass,
labelClass,
cinemaSlug,
}: Props) {
const fileRef = useRef<HTMLInputElement | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [dragging, setDragging] = useState(false);
export function PhotosEditor({ photos, onChange, inputClass, labelClass }: Props) {
function updateAt(index: number, value: string) {
onChange(photos.map((item, i) => (i === index ? value : item)));
}
async function uploadFiles(files: FileList | File[]) {
const list = Array.from(files).filter((file) => file.size > 0);
if (list.length === 0) return;
const tooBig = list.find((file) => file.size > MAX_UPLOAD_BYTES);
if (tooBig) {
setError(
`ไฟล์ "${tooBig.name}" ใหญ่เกิน ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)} MB`,
);
return;
}
setBusy(true);
setError(null);
const uploaded: string[] = [];
try {
for (const file of list) {
const form = new FormData();
form.append("file", file);
if (cinemaSlug) form.append("slug", cinemaSlug);
const res = await fetch("/api/admin/uploads", {
method: "POST",
body: form,
});
if (!res.ok) {
const message = await res.text();
throw new Error(message || `อัปโหลดไม่สำเร็จ (${res.status})`);
}
const data = (await res.json()) as { url?: string };
if (!data.url) throw new Error("เซิร์ฟเวอร์ไม่ได้คืน URL ของรูป");
uploaded.push(data.url);
}
if (uploaded.length > 0) onChange([...photos, ...uploaded]);
} catch (uploadError) {
setError(
uploadError instanceof Error ? uploadError.message : "อัปโหลดไม่สำเร็จ",
);
} finally {
setBusy(false);
if (fileRef.current) fileRef.current.value = "";
}
}
return (
<div className="flex flex-col gap-2">
<div
className={`flex flex-col gap-2 rounded-lg border border-dashed p-2 transition ${
dragging ? "border-[#A92626] bg-[#1B1B1B]/60" : "border-transparent"
}`}
onDragOver={(event) => {
if (!event.dataTransfer?.types.includes("Files")) return;
event.preventDefault();
setDragging(true);
}}
onDragLeave={() => setDragging(false)}
onDrop={(event) => {
if (!event.dataTransfer?.files?.length) return;
event.preventDefault();
setDragging(false);
void uploadFiles(event.dataTransfer.files);
}}
onPaste={(event) => {
const files = Array.from(event.clipboardData?.files ?? []);
if (files.length === 0) return;
event.preventDefault();
void uploadFiles(files);
}}
>
<span className="text-xs text-[#999]">รูปภาพโรงหนัง</span>
{photos.length === 0 ? (
<span className="text-[11px] text-[#777]">
ยังไม่มีรูป — หน้าเว็บจะแสดงช่องแทน (ภาพที่ 1/2/3)
ยังไม่มีรูป — อัปโหลดจากเครื่อง หรือวาง URL ด้านล่าง (ภาพที่ 1/2/3)
</span>
) : null}
@@ -93,14 +183,48 @@ export function PhotosEditor({ photos, onChange, inputClass, labelClass }: Props
</div>
))}
<button
type="button"
className={`${smallButtonClass} w-fit`}
onClick={() => onChange([...photos, ""])}
>
<IconPlus size={14} />
เพิ่มรูป
</button>
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
className={uploadButtonClass}
disabled={busy}
onClick={() => fileRef.current?.click()}
>
<IconPhotoUp size={16} />
{busy ? "กำลังอัปโหลด…" : "อัปโหลดรูปจากเครื่อง"}
</button>
<button
type="button"
className={`${smallButtonClass} w-fit`}
onClick={() => onChange([...photos, ""])}
>
<IconPlus size={14} />
เพิ่มช่อง URL
</button>
<span className="text-[11px] text-[#777]">
ลากไฟล์มาวาง หรือ Ctrl+V ในกล่องนี้ · JPG/PNG/WebP/AVIF ≤{" "}
{Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)} MB
</span>
</div>
<input
ref={fileRef}
type="file"
accept="image/jpeg,image/png,image/webp,image/avif"
multiple
className="hidden"
onChange={(event) => {
if (event.target.files) void uploadFiles(event.target.files);
}}
/>
{error ? (
<span role="alert" className="text-[11px] text-[#D47272]">
{error}
</span>
) : null}
</div>
);
}
+115
View File
@@ -0,0 +1,115 @@
/**
* ทดสอบกติกาการอัปโหลดรูป — กัน 3 เคสที่พังเงียบ:
* - รับไฟล์ที่ไม่ใช่รูป (เปลี่ยนนามสกุลมา)
* - path traversal ตอนเสิร์ฟไฟล์ (`../`)
* - ชื่อไฟล์ชนกัน (ต้องมี timestamp + random)
*/
import { describe, expect, it } from "vitest";
import {
MAX_UPLOAD_BYTES,
extensionForType,
isValidImageUpload,
makeUploadName,
safeUploadPath,
sanitizeSlug,
sniffImageType,
typeForExtension,
} from "@/lib/upload";
const jpeg = new Uint8Array([
0xff, 0xd8, 0xff, 0xe0, 0, 0x10, 0x4a, 0x46, 0x49, 0x46, 0, 1,
]);
const png = new Uint8Array([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0,
]);
const webp = new Uint8Array([
0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50,
]);
const gif = new Uint8Array([
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0, 0, 0, 0, 0, 0,
]);
describe("sniffImageType", () => {
it("ตรวจ JPEG / PNG / WebP จาก magic bytes", () => {
expect(sniffImageType(jpeg)).toBe("image/jpeg");
expect(sniffImageType(png)).toBe("image/png");
expect(sniffImageType(webp)).toBe("image/webp");
});
it("ไฟล์ที่ไม่ใช่รูป (หรือสั้นเกิน) → null", () => {
expect(sniffImageType(gif)).toBeNull();
expect(sniffImageType(new Uint8Array([1, 2, 3]))).toBeNull();
});
});
describe("isValidImageUpload", () => {
it("รับรูปที่ถูกต้อง", () => {
expect(isValidImageUpload(jpeg)).toBe(true);
});
it("ปฏิเสธไฟล์ว่างและไฟล์ที่ใหญ่เกินเพดาน", () => {
expect(isValidImageUpload(new Uint8Array([]))).toBe(false);
const huge = new Uint8Array(MAX_UPLOAD_BYTES + 1);
huge.set(jpeg);
expect(isValidImageUpload(huge)).toBe(false);
});
});
describe("extensionForType / typeForExtension", () => {
it("แมปชนิด ↔ นามสกุลไป-กลับได้", () => {
expect(extensionForType("image/jpeg")).toBe("jpg");
expect(typeForExtension("webp")).toBe("image/webp");
});
it("ชนิดที่ไม่รองรับ → null", () => {
expect(extensionForType("image/gif")).toBeNull();
expect(extensionForType("text/html")).toBeNull();
});
});
describe("sanitizeSlug", () => {
it("เหลือ a-z 0-9 และ - เท่านั้น", () => {
expect(sanitizeSlug("Phahol Theatre!")).toBe("phahol-theatre");
expect(sanitizeSlug("../../etc/passwd")).toBe("etc-passwd");
});
it("ว่าง → ใช้ค่า fallback", () => {
expect(sanitizeSlug("!!!")).toBe("cinema");
});
});
describe("makeUploadName", () => {
it("มี slug + random + timestamp + นามสกุลที่ถูกต้อง", () => {
const name = makeUploadName(
"house-cinema-samyan",
"image/webp",
1700000000000,
"abc123",
);
expect(name).toBe("house-cinema-samyan-abc123-1700000000000.webp");
});
it("ชื่อไม่ชนกันเมื่อเรียกซ้ำในมิลลิวินาทีเดียวกัน", () => {
const a = makeUploadName("x", "image/jpeg", 1, "aaa111");
const b = makeUploadName("x", "image/jpeg", 1, "bbb222");
expect(a).not.toBe(b);
});
it("ชนิดที่ไม่รองรับ → โยน error", () => {
expect(() => makeUploadName("x", "image/gif")).toThrow();
});
});
describe("safeUploadPath", () => {
it("รับพาธปกติ", () => {
expect(safeUploadPath("cinemas/abc-1.webp")).toBe("cinemas/abc-1.webp");
});
it("ปฏิเสธ path traversal และ absolute path", () => {
expect(safeUploadPath("../secrets.json")).toBeNull();
expect(safeUploadPath("cinemas/../../x")).toBeNull();
expect(safeUploadPath("/etc/passwd")).toBeNull();
expect(safeUploadPath("")).toBeNull();
});
});
+104
View File
@@ -0,0 +1,104 @@
/**
* กติกาการอัปโหลดรูป (ใช้ร่วมทั้ง client และ server)
*
* เก็บไว้ที่ `data/uploads/cinemas/` แล้วเสิร์ฟผ่าน `/uploads/cinemas/<ไฟล์>`
* (ไม่เขียนลง `public/` เพราะตอน production โฟลเดอร์ public ถูก copy ตอน build — เขียน runtime ไม่ติด)
*/
export const MAX_UPLOAD_BYTES = 8 * 1024 * 1024; // 8 MB
export const UPLOAD_URL_PREFIX = "/uploads/cinemas";
export const ALLOWED_IMAGE_TYPES = [
"image/jpeg",
"image/png",
"image/webp",
"image/avif",
] as const;
const EXT_BY_TYPE: Record<string, string> = {
"image/jpeg": "jpg",
"image/png": "png",
"image/webp": "webp",
"image/avif": "avif",
};
export function extensionForType(type: string): string | null {
return EXT_BY_TYPE[type.trim().toLowerCase()] ?? null;
}
export function typeForExtension(ext: string): string {
const found = Object.entries(EXT_BY_TYPE).find(([, value]) => value === ext);
return found ? found[0] : "application/octet-stream";
}
/** ชื่อไฟล์ปลอดภัย: ตัวพิมพ์เล็ก a-z 0-9 และ `-` เท่านั้น */
export function sanitizeSlug(value: string, fallback = "cinema"): string {
const clean = String(value ?? "")
.toLowerCase()
.replace(/[^a-z0-9-]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 64);
return clean === "" ? fallback : clean;
}
/** ตรวจชนิดไฟล์จาก "magic bytes" — ไม่เชื่อ content-type ที่ client ส่งมา */
export function sniffImageType(bytes: Uint8Array): string | null {
if (bytes.length < 12) return null;
// JPEG: FF D8 FF
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "image/jpeg";
// PNG: 89 50 4E 47 0D 0A 1A 0A
if (
bytes[0] === 0x89 &&
bytes[1] === 0x50 &&
bytes[2] === 0x4e &&
bytes[3] === 0x47
) {
return "image/png";
}
// WebP: "RIFF" .... "WEBP"
if (
bytes[0] === 0x52 &&
bytes[1] === 0x49 &&
bytes[2] === 0x46 &&
bytes[3] === 0x46 &&
bytes[8] === 0x57 &&
bytes[9] === 0x45 &&
bytes[10] === 0x42 &&
bytes[11] === 0x50
) {
return "image/webp";
}
// AVIF: ....ftyp + avif/avis
const brand = String.fromCharCode(...bytes.slice(4, 12));
if (brand.startsWith("ftyp") && (brand.includes("avif") || brand.includes("avis"))) {
return "image/avif";
}
return null;
}
/** true = ไฟล์นี้รับได้ (ขนาด + ชนิดจริง) */
export function isValidImageUpload(bytes: Uint8Array): boolean {
if (bytes.byteLength === 0 || bytes.byteLength > MAX_UPLOAD_BYTES) return false;
return sniffImageType(bytes) !== null;
}
/** ชื่อไฟล์ปลายทาง เช่น `cinema-a1b2c3-1712345678901.webp` */
export function makeUploadName(
slug: string,
type: string,
now: number = Date.now(),
random: string = Math.random().toString(36).slice(2, 8),
): string {
const ext = extensionForType(type);
if (!ext) throw new Error(`ชนิดไฟล์ไม่รองรับ: ${type}`);
return `${sanitizeSlug(slug)}-${random}-${now}.${ext}`;
}
/** ป้องกัน path traversal ตอนอ่านไฟล์ที่อัปโหลด */
export function safeUploadPath(requested: string): string | null {
const cleaned = String(requested ?? "").replace(/\\/g, "/").trim();
if (cleaned === "" || cleaned.includes("..") || cleaned.startsWith("/")) return null;
if (!/^[a-zA-Z0-9._/-]+$/.test(cleaned)) return null;
return cleaned;
}
+1
View File
@@ -540,6 +540,7 @@ export default function AdminRoute() {
<div className="sm:col-span-2">
<PhotosEditor
photos={cinema.photos}
cinemaSlug={cinema.slug}
onChange={(photos) =>
patchCinema(cinema.slug, (current) => ({
...current,