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:
1 parent
251932e548
commit
2c5918a614
10 files changed
+483
-22
No files matched your search
@@ -252,6 +252,8 @@ Single source of truth per concern — do not duplicate these:
|
||||
- ตรวจรูปเสียก่อน commit: `node scripts/audit-photos.mjs` (exit 1 = มีรูปพัง)
|
||||
- ขนาดรูป: กว้างไม่เกิน **1600px** และบีบอัด (JPEG q82 / WebP q82) — โฟลเดอร์ `public/images/cinemas` ควรอยู่ราว **≤ 3 MB**
|
||||
- **ทุก `<img>` ของโรงหนังต้องใช้ `<PhotoImage>`** (`app/components/site/PhotoImage.tsx`) — มี `onError` สลับไปโลโก้แทนรูปแตก และจำ `src` ที่พังเพื่อให้เปลี่ยนรูปใหม่แล้วโหลดได้อีก (ห้ามเขียน `<img src={photo}>` ตรง ๆ ใน component ใหม่)
|
||||
- **อัปโหลดจากหลังบ้าน**: `PhotosEditor` → `POST /api/admin/uploads` (multipart, ≤ 8 MB, ตรวจ magic bytes) → เก็บ `data/uploads/cinemas/` → คืน `/uploads/cinemas/<slug>-<random>-<ts>.<ext>` (gitignored) เสิร์ฟผ่าน Nitro route `server/routes/uploads/[...path].get.ts` — **ห้ามย้ายไปเขียนใน `public/`** เพราะตอน production โฟลเดอร์นั้นถูก copy ตอน build (เขียน runtime ไม่ติด)
|
||||
- `app/lib/upload.ts` คือกติกากลาง (เพดานขนาด · ชนิดที่รับ · sanitize ชื่อ · กัน path traversal) — ใช้ทั้ง client และ server ห้ามประกาศซ้ำ
|
||||
|
||||
## ลำดับการ์ดหน้าแรก (สลับทุกวัน)
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ pnpm dev # http://localhost:8080
|
||||
|
||||
`http://localhost:8080/admin` — ล็อกอินด้วย `ADMIN_USERNAME` / `ADMIN_PASSWORD` (ค่าเริ่มต้น `it is me` / `it is me&it is me`)
|
||||
|
||||
7 แท็บ: **โรงหนัง** (ชื่อ/slug/หมวด/สิ่งอำนวยความสะดวก/การเดินทาง/ติดต่อ/รูปภาพ/ที่ตั้ง/คำอธิบาย) · **หน้าเกี่ยวกับเรา** · **สำหรับคนรักหนัง** · **สำหรับคนทำโรงหนัง** · **คำศัพท์หลายภาษา** · **Footer-ไอคอน** · **สถิติการค้นหา**
|
||||
7 แท็บ: **โรงหนัง** (ชื่อ/slug/หมวด/สิ่งอำนวยความสะดวก/การเดินทาง/ติดต่อ/**รูปภาพ — อัปโหลดจากเครื่อง/ลากวาง/วาง URL**/ที่ตั้ง/คำอธิบาย) · **หน้าเกี่ยวกับเรา** · **สำหรับคนรักหนัง** · **สำหรับคนทำโรงหนัง** · **คำศัพท์หลายภาษา** · **Footer-ไอคอน** · **สถิติการค้นหา**
|
||||
|
||||
คู่มือทีละงาน: **[docs/admin-guide.md](docs/admin-guide.md)**
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
+8
-6
@@ -46,14 +46,16 @@
|
||||
|
||||
## 2. รูปภาพโรงหนัง
|
||||
|
||||
หมวด **การเดินทาง & การติดต่อ** → ส่วน **รูปภาพโรงหนัง** → **+ เพิ่มรูป**
|
||||
หมวด **การเดินทาง & การติดต่อ** → ส่วน **รูปภาพโรงหนัง** → **อัปโหลดรูปจากเครื่อง**
|
||||
|
||||
1. ใส่ URL (`https://…`) หรือ path ในโปรเจกต์ (`/images/ชื่อไฟล์.jpg`)
|
||||
2. **รูปแรก = รูปปกการ์ดหน้าแรก** และภาพหลักในแกลเลอรีหน้า detail
|
||||
3. มีไม่ครบ 3 รูป ช่องที่เหลือจะแสดงโลโก้ AlterFlixHub แทน
|
||||
4. สลับลำดับด้วย ↑ ↓ · ลบด้วยถังขยะ · แล้วกด **บันทึกทั้งหมด**
|
||||
1. กด **อัปโหลดรูปจากเครื่อง** แล้วเลือกไฟล์ (เลือกหลายไฟล์พร้อมกันได้) — หรือ **ลากไฟล์มาวาง** ในกล่องนั้น หรือ **Ctrl+V** วางรูปจากคลิปบอร์ด
|
||||
2. รองรับ **JPG / PNG / WebP / AVIF** ขนาดไม่เกิน **8 MB** ต่อไฟล์ · ไฟล์จะถูกเก็บที่ `data/uploads/cinemas/` และได้ URL รูปแบบ `/uploads/cinemas/<ไฟล์>` ใช้อ้างในหน้าเว็บได้ทันที
|
||||
3. ถ้าอยากใช้รูปที่วางบนเว็บอยู่แล้ว กด **เพิ่มช่อง URL** แล้ววางลิงก์ (`/images/…` หรือ URL เต็ม) — **ไม่แนะนำลิงก์จาก Google Maps/Facebook** เพราะลิงก์หมดอายุและทำให้รูปแตก
|
||||
4. **รูปแรก = รูปปกการ์ดหน้าแรก** และภาพหลักในแกลเลอรีหน้า detail — สลับลำดับด้วยปุ่ม ↑/↓
|
||||
5. มีไม่ครบ 3 รูป ช่องที่เหลือจะแสดงโลโก้ AlterFlixHub แทน
|
||||
6. อย่าลืมกด **บันทึก** ท้ายฟอร์ม — รูปจะขึ้นหน้าเว็บทันทีหลังบันทึก
|
||||
|
||||
ไฟล์ในเครื่อง: วางที่ `public/images/…` แล้วใส่ `/images/…`
|
||||
ไฟล์ในเครื่อง (สำหรับรูปที่เตรียมไว้ล่วงหน้า): วางที่ `public/images/…` แล้วใส่ `/images/…` · รูปที่อัปโหลดผ่านหลังบ้านจะอยู่ที่ `data/uploads/cinemas/` (สำรองข้อมูลแยกจาก repo)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
| Method | Path | Body / Query | ทำอะไร |
|
||||
|---|---|---|---|
|
||||
| POST | `/api/analytics/collect` | `{ type, locale, query?, category?, result_count?, slug?, source?, position? }` | รับ event สถิติ 1 ครั้ง — เซิร์ฟเวอร์เป็นผู้ใส่ `at` และ hash ผู้เข้าชม (`sha256(เกลือรายวัน \| ip \| ua)` 16 ตัวอักษร) ไม่ใช้คุกกี้ ไม่เก็บ IP/UA ดิบ |
|
||||
| GET | `/uploads/cinemas/<ไฟล์>` | — | เสิร์ฟรูปที่อัปโหลดจากหลังบ้าน (อ่านจาก `data/uploads/cinemas/`) · `Cache-Control: immutable` · กัน path traversal |
|
||||
|
||||
`type` ที่รองรับ: `search` · `cinema_select` · `cinema_view` · `near_me`
|
||||
|
||||
@@ -19,6 +20,7 @@
|
||||
| POST | `/api/admin/logout` | — | ลบคุกกี้ session |
|
||||
| GET | `/api/admin/session` | — | ตรวจว่ายังล็อกอินอยู่ |
|
||||
| GET | `/api/admin/content` | — | อ่าน `ContentStore` ทั้งก้อน (`cinemas`, `site`, `about`, `forCinemas`, `forFilmLovers`) |
|
||||
| POST | `/api/admin/uploads` | `multipart/form-data`: `file` (บังคับ, ≤ 8 MB), `slug` (ไม่บังคับ) | อัปโหลดรูปโรงหนัง — ตรวจชนิดจริงจาก magic bytes (JPEG/PNG/WebP/AVIF) เก็บที่ `data/uploads/cinemas/` คืน `{ url, bytes, type }` โดย `url` = `/uploads/cinemas/<ไฟล์>` |
|
||||
| PUT | `/api/admin/content` | `{ cinemas?, site?, about?, forCinemas?, forFilmLovers? }` | บันทึกเฉพาะส่วนที่ส่งมา — ผ่าน `sanitizeCinemas` / `sanitizeSite` / `sanitizeAbout` / `sanitizeForCinemas` / `sanitizeForFilmLovers` แล้วเขียนไฟล์แบบ atomic |
|
||||
| POST | `/api/admin/cinemas/import` | `{ cinemas: Cinema[] }` หรือรายการเดียว | นำเข้าโรงหนังโดยใช้ slug เป็นกุญแจ (มีอยู่ = ทับ) |
|
||||
| GET | `/api/admin/analytics` | `?days=1\|7\|30\|90` | สรุปสถิติ (`summarize()`) — คำค้นยอดนิยม, คำค้นไม่พบผล, CTR, โรงที่ถูกเปิด/คลิก |
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* POST /api/admin/uploads — อัปโหลดรูปโรงหนังจากเครื่อง (multipart/form-data)
|
||||
*
|
||||
* ฟิลด์:
|
||||
* file (บังคับ) — ไฟล์รูป jpeg/png/webp/avif ขนาด ≤ 8 MB
|
||||
* slug (ไม่บังคับ) — ใช้ตั้งชื่อไฟล์ให้อ่านง่าย
|
||||
*
|
||||
* คืน: { url: "/uploads/cinemas/<ไฟล์>", bytes, type }
|
||||
*/
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { createError, defineEventHandler, readMultipartFormData } from "h3";
|
||||
|
||||
import { requireAdmin } from "@/lib/admin-auth.server";
|
||||
import {
|
||||
MAX_UPLOAD_BYTES,
|
||||
UPLOAD_URL_PREFIX,
|
||||
isValidImageUpload,
|
||||
makeUploadName,
|
||||
sniffImageType,
|
||||
} from "@/lib/upload";
|
||||
|
||||
const UPLOAD_DIR = path.join(process.cwd(), "data", "uploads", "cinemas");
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
requireAdmin(event);
|
||||
|
||||
const parts = await readMultipartFormData(event);
|
||||
const filePart = parts?.find((part) => part.name === "file" && part.data);
|
||||
if (!filePart) {
|
||||
throw createError({ statusCode: 400, statusMessage: "ไม่พบไฟล์ที่ส่งมา (field: file)" });
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(filePart.data);
|
||||
if (bytes.byteLength === 0) {
|
||||
throw createError({ statusCode: 400, statusMessage: "ไฟล์ว่าง" });
|
||||
}
|
||||
if (bytes.byteLength > MAX_UPLOAD_BYTES) {
|
||||
throw createError({
|
||||
statusCode: 413,
|
||||
statusMessage: `ไฟล์ใหญ่เกิน ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)} MB`,
|
||||
});
|
||||
}
|
||||
|
||||
// ไม่เชื่อ content-type จาก client — ตรวจจากเนื้อไฟล์จริง
|
||||
const type = sniffImageType(bytes);
|
||||
if (!type || !isValidImageUpload(bytes)) {
|
||||
throw createError({
|
||||
statusCode: 415,
|
||||
statusMessage: "รับเฉพาะรูป JPEG / PNG / WebP / AVIF",
|
||||
});
|
||||
}
|
||||
|
||||
const slugPart = parts?.find((part) => part.name === "slug")?.data;
|
||||
const slug = slugPart ? Buffer.from(slugPart).toString("utf8") : "cinema";
|
||||
const fileName = makeUploadName(slug, type);
|
||||
|
||||
await fs.mkdir(UPLOAD_DIR, { recursive: true });
|
||||
await fs.writeFile(path.join(UPLOAD_DIR, fileName), bytes);
|
||||
|
||||
return {
|
||||
url: `${UPLOAD_URL_PREFIX}/${fileName}`,
|
||||
bytes: bytes.byteLength,
|
||||
type,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* GET /uploads/** — เสิร์ฟรูปที่อัปโหลดจากหลังบ้าน (เก็บที่ data/uploads/)
|
||||
*
|
||||
* ใช้ Nitro route เพราะโฟลเดอร์ public/ ถูก copy ตอน build
|
||||
* → ไฟล์ที่เขียนตอน runtime ต้องเสิร์ฟเอง
|
||||
*/
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { createError, defineEventHandler, getRouterParam, setResponseHeaders } from "h3";
|
||||
|
||||
import { safeUploadPath, typeForExtension } from "../../../app/lib/upload";
|
||||
|
||||
const UPLOAD_ROOT = path.join(process.cwd(), "data", "uploads");
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const raw = getRouterParam(event, "path") ?? "";
|
||||
const relative = safeUploadPath(decodeURIComponent(raw));
|
||||
if (!relative) {
|
||||
throw createError({ statusCode: 400, statusMessage: "พาธไฟล์ไม่ถูกต้อง" });
|
||||
}
|
||||
|
||||
const filePath = path.join(UPLOAD_ROOT, relative);
|
||||
const resolved = path.resolve(filePath);
|
||||
if (!resolved.startsWith(path.resolve(UPLOAD_ROOT))) {
|
||||
throw createError({ statusCode: 403, statusMessage: "ไม่อนุญาต" });
|
||||
}
|
||||
|
||||
let data: Buffer;
|
||||
try {
|
||||
data = await fs.readFile(resolved);
|
||||
} catch {
|
||||
throw createError({ statusCode: 404, statusMessage: "ไม่พบไฟล์" });
|
||||
}
|
||||
|
||||
const ext = path.extname(resolved).replace(".", "").toLowerCase();
|
||||
setResponseHeaders(event, {
|
||||
"Content-Type": typeForExtension(ext),
|
||||
"Content-Length": String(data.byteLength),
|
||||
// ชื่อไฟล์มี timestamp+random → cache ได้ยาว
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
});
|
||||
return data;
|
||||
});
|
||||
Reference in new issue
Block a user