/** * อ่าน/เขียนเนื้อหาที่แก้ได้จากหลังบ้าน (`data/content/content.json`) * * หมายเหตุเรื่องแคช: `cache` ด้านล่างเก็บผล sanitize ไว้ต่อ process (คีย์ = ความยาวไฟล์) * ดังนั้นถ้าแก้ "ข้อความตั้งต้น" ใน `messages.ts` ต้องรีสตาร์ต/ให้ dev server โหลดโมดูลใหม่ * ไฟล์นี้จึงจะคำนวณ seed ใหม่ — การแก้ผ่านหน้า admin ไม่ต้องรีสตาร์ต (ไฟล์เปลี่ยนเอง) */ import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { sanitizeArticleBlocks } from "@/lib/article"; import { VENUE_TYPES, type Cinema, type VenueType } from "@/lib/cinemas"; import { contactHref } from "@/lib/contact-link"; import { seedAbout, seedContent, seedForCinemas, seedForFilmLovers, } from "@/lib/content-seed"; import type { AboutContent, ArticleContent, ContentStore, FooterItem, LocaleEntry, SiteContent, TermEntry, } from "@/lib/content-types"; import type { Locale } from "@/lib/i18n/messages"; import { FACILITY_KEYS } from "@/lib/i18n/messages"; const CONTENT_DIR = path.join(process.cwd(), "data", "content"); const CONTENT_FILE = path.join(CONTENT_DIR, "content.json"); let cache: { store: ContentStore; mtimeMs: number } | null = null; function asString(value: unknown, fallback = ""): string { return typeof value === "string" ? value : fallback; } function asStringList(value: unknown): string[] { return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : []; } function asCoordinates(value: unknown): Cinema["coordinates"] { if (!value || typeof value !== "object") return null; const raw = value as { latitude?: unknown; longitude?: unknown }; const latitude = Number(raw.latitude); const longitude = Number(raw.longitude); if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null; return { latitude, longitude }; } /** ตรวจและแปลงสิ่งอำนวยความสะดวก — เก็บเฉพาะคีย์ที่รู้จัก เรียงตาม FACILITY_KEYS */ function sanitizeFacilities(value: unknown): Cinema["facilities"] { if (!Array.isArray(value)) return []; const picked = new Set( value.filter((item): item is string => typeof item === "string"), ); return FACILITY_KEYS.filter((key) => picked.has(key)); } /** ตรวจข้อความเฉพาะโรงของแต่ละหัวข้อ — เก็บเฉพาะคีย์/ฟิลด์ที่รู้จัก */ function sanitizeFacilityDetails(value: unknown): Cinema["facility_details"] { if (!value || typeof value !== "object") return {}; const raw = value as Record; const result: NonNullable = {}; for (const key of FACILITY_KEYS) { const entry = raw[key]; if (!entry || typeof entry !== "object") continue; const item = entry as Record; const label = asString(item.label).trim(); const subTh = asString(item.sub_th); const subEn = asString(item.sub_en); if (label || subTh || subEn) { result[key] = { ...(label ? { label } : {}), ...(subTh ? { sub_th: subTh } : {}), ...(subEn ? { sub_en: subEn } : {}), }; } } return result; } /** ตรวจและแปลงโรงหนังจาก JSON ที่ผู้ใช้แก้/วาง — ฟิลด์ที่ไม่รู้จักถูกทิ้ง */ export function sanitizeCinemas(input: unknown): Cinema[] { if (!Array.isArray(input)) throw new Error("cinemas ต้องเป็น array"); return input.map((item, index) => { if (!item || typeof item !== "object") { throw new Error(`โรงหนังลำดับที่ ${index + 1} ไม่ใช่วัตถุ`); } const raw = item as Record; const slug = asString(raw.slug).trim(); const name = asString(raw.name).trim(); if (!slug) throw new Error(`โรงหนังลำดับที่ ${index + 1} ไม่มี slug`); if (!name) throw new Error(`โรงหนัง ${slug} ไม่มีชื่อ`); return { slug, name, name_th: asString(raw.name_th), tags: asStringList(raw.tags), location_label: asString(raw.location_label), location_label_en: asString(raw.location_label_en), coordinates: asCoordinates(raw.coordinates), description: asString(raw.description), description_en: asString(raw.description_en), map_url: typeof raw.map_url === "string" ? raw.map_url : null, address_lines: asStringList(raw.address_lines), address_lines_en: asStringList(raw.address_lines_en), transport: Array.isArray(raw.transport) ? raw.transport.map((route) => { const entry = (route ?? {}) as Record; const icon = asString(entry.icon_name, "bus"); return { icon_name: (["private_car", "metro", "bus"].includes(icon) ? icon : "bus") as Cinema["transport"][number]["icon_name"], value: asString(entry.value), value_en: asString(entry.value_en), }; }) : [], contacts: Array.isArray(raw.contacts) ? raw.contacts.map((contact) => { const entry = (contact ?? {}) as Record; const label = asString(entry.label); const value = asString(entry.value); const href = typeof entry.href === "string" ? entry.href : null; // บังคับ href ให้เป็นลิงก์ที่กดใช้ได้จริง (tel:/mailto:/https:) ทุกครั้งที่บันทึก return { label, value, href: contactHref({ label, value, href }), }; }) : [], payments: asStringList(raw.payments), facilities: sanitizeFacilities(raw.facilities), facility_details: sanitizeFacilityDetails(raw.facility_details), hidden: raw.hidden === true, venue_type: VENUE_TYPES.includes(raw.venue_type as VenueType) ? (raw.venue_type as VenueType) : null, contact_heading: asString(raw.contact_heading), photos: asStringList(raw.photos), }; }); } export function sanitizeSite(input: unknown): SiteContent { const seed = seedContent().site; if (!input || typeof input !== "object") return seed; const raw = input as Record; const locales: LocaleEntry[] = Array.isArray(raw.locales) ? raw.locales .map((locale) => { const entry = (locale ?? {}) as Record; const code = asString(entry.code).trim(); return code ? { code, label: asString(entry.label, code) } : null; }) .filter((locale): locale is LocaleEntry => locale !== null) : seed.locales; const terms: TermEntry[] = Array.isArray(raw.terms) ? raw.terms .map((term) => { const entry = (term ?? {}) as Record; const key = asString(entry.key).trim(); if (!key) return null; const values: Record = {}; const rawValues = (entry.values ?? {}) as Record; for (const [locale, value] of Object.entries(rawValues)) { values[locale] = asString(value); } return { key, values }; }) .filter((term): term is TermEntry => term !== null) : seed.terms; const footer: FooterItem[] = Array.isArray(raw.footer) ? raw.footer .map((item, index) => { const entry = (item ?? {}) as Record; const label = asString(entry.label).trim(); if (!label) return null; return { id: asString(entry.id, `footer-${index + 1}`), icon_name: asString(entry.icon_name, "IconLink"), label, href: asString(entry.href), }; }) .filter((item): item is FooterItem => item !== null) : seed.footer; return { locales: locales.length > 0 ? locales : seed.locales, terms: terms.length > 0 ? terms : seed.terms, footer, }; } export function sanitizeAbout(input: unknown): Record { const seed = seedAbout(); if (!input || typeof input !== "object") return seed; const raw = input as Record; function one(value: unknown, fallback: AboutContent): AboutContent { if (!value || typeof value !== "object") return fallback; const entry = value as Record; const sections = Array.isArray(entry.sections) ? entry.sections .map((section) => { const item = (section ?? {}) as Record; const heading = asString(item.heading).trim(); const body = asString(item.body).trim(); return heading || body ? { heading, body } : null; }) .filter( (section): section is { heading: string; body: string } => section !== null, ) : fallback.sections; return { title: asString(entry.title, "").trim() || fallback.title, lead: asString(entry.lead).trim() || fallback.lead, sections: sections.length > 0 ? sections : fallback.sections, contactHeading: asString(entry.contactHeading).trim() || fallback.contactHeading, contactNote: asString(entry.contactNote).trim() || fallback.contactNote, }; } return { th: one(raw.th, seed.th), en: one(raw.en, seed.en), }; } /** * ตรวจเนื้อหาหน้าบทความ (ใช้ทั้ง "สำหรับคนทำโรงหนัง" และ "สำหรับคนรักหนัง") * * ทำไมต้องมี seed: ถ้า editor ส่งค่าที่ใช้ไม่ได้มา (บล็อกว่างทั้งหมด, ไม่ได้ส่งภาษาใดภาษา * มาบ้าง) หน้าเว็บจะกลายเป็นหน้าว่าง — จึงต้องเติมข้อความตั้งต้นของภาษานั้นให้เสมอ * บล็อกที่ผิดรูปแบบ/ว่างจะถูกตัดทิ้งด้วย sanitizeArticleBlocks */ function sanitizeArticlePage( input: unknown, seed: Record, ): Record { if (!input || typeof input !== "object") return seed; const raw = input as Record; function one(value: unknown, fallback: ArticleContent): ArticleContent { if (!value || typeof value !== "object") return fallback; const entry = value as Record; const blocks = sanitizeArticleBlocks(entry.blocks); return { title: asString(entry.title, "").trim() || fallback.title, lead: asString(entry.lead).trim() || fallback.lead, blocks: blocks.length > 0 ? blocks : fallback.blocks, contactHeading: asString(entry.contactHeading).trim() || fallback.contactHeading, contactNote: asString(entry.contactNote).trim() || fallback.contactNote, }; } return { th: one(raw.th, seed.th), en: one(raw.en, seed.en), }; } /** เนื้อหาหน้า "สำหรับคนทำโรงหนัง" */ export function sanitizeForCinemas( input: unknown, ): Record { return sanitizeArticlePage(input, seedForCinemas()); } /** เนื้อหาหน้า "สำหรับคนรักหนัง" */ export function sanitizeForFilmLovers( input: unknown, ): Record { return sanitizeArticlePage(input, seedForFilmLovers()); } /** อ่านเนื้อหาทั้งหมด — สร้างไฟล์เริ่มต้นให้อัตโนมัติเมื่อยังไม่มี */ export async function readContent(): Promise { let raw: string; try { raw = await readFile(CONTENT_FILE, "utf8"); } catch (error) { // ไม่มีไฟล์ = ครั้งแรกของโปรเจกต์ → สร้างจาก seed if ((error as NodeJS.ErrnoException)?.code === "ENOENT") { const store = seedContent(); await writeContent(store); return store; } throw error; } const mtimeMs = raw.length; if (cache && cache.mtimeMs === mtimeMs) return cache.store; // ไฟล์เสีย/รูปแบบไม่ถูกต้อง → โยน error ออกไป ห้ามเขียนทับข้อมูลเดิมด้วย seed const parsed = JSON.parse(raw) as unknown; const store = sanitizeStore(parsed); cache = { store, mtimeMs }; return store; } function sanitizeStore(input: unknown): ContentStore { const raw = (input ?? {}) as Record; return { cinemas: sanitizeCinemas(raw.cinemas ?? []), site: sanitizeSite(raw.site ?? {}), about: sanitizeAbout(raw.about ?? {}), forCinemas: sanitizeForCinemas(raw.forCinemas ?? {}), forFilmLovers: sanitizeForFilmLovers(raw.forFilmLovers ?? {}), }; } /** เขียนแบบ atomic (tmp → rename) เพื่อไม่ให้อ่านไฟล์ครึ่ง ๆ กลาง ๆ */ export async function writeContent(store: ContentStore): Promise { await mkdir(CONTENT_DIR, { recursive: true }); const temporary = `${CONTENT_FILE}.tmp`; await writeFile(temporary, `${JSON.stringify(store, null, 2)}\n`, "utf8"); await rename(temporary, CONTENT_FILE); cache = null; }