Files
Bkk1234 251932e548 fix(photos): รูปโรงหนังแตก — mirror รูปภายนอกมาเก็บในโปรเจกต์ + fallback
สาเหตุ: photos[] อ้างลิงก์ hotlink (googleusercontent/gstatic/fbcdn ฯลฯ)
ซึ่งตอบ 200 แต่ 0 ไบต์เมื่อลิงก์หมดอายุ/ถูกจำกัด rate → รูปแตกเงียบ ๆ
เช่น /cinema/phahol-theatre

- scripts/mirror-photos.mjs: ดาวน์โหลด 20 รูปจาก 12 โรง มาเก็บ public/images/cinemas
  แล้วแก้ content.json ชี้ path ในโปรเจกต์ (สำรอง .bak-photos-* ก่อนเขียน) → เหลือรูปภายนอก 0
- บีบอัดรูปใหญ่ (<=1600px, q82): 6.12 MB → 2.91 MB
- PhotoImage: img + onError fallback เป็นโลโก้ (ใช้ใน CinemaCard/Gallery) กันรูปแตกทุกกรณี
- scripts/audit-photos.mjs: ตรวจรูปเสีย exit 1
- DESIGN.md: กฎรูปภาพ (ห้าม hotlink, ต้องใช้ PhotoImage, เพดานขนาด)
2026-11-15 22:32:52 +07:00

124 lines
5.0 KiB
JavaScript

/**
* ทำสำเนารูปที่อ้างจากภายนอก (http/https) ลงเครื่อง แล้วเปลี่ยน content.json ให้ชี้ไฟล์ในโปรเจกต์
*
* ทำไม: โฮสต์อย่าง Google Maps / googleusercontent / fbcdn / gstatic เป็น **hotlink-hostile**
* (ลิงก์มีอายุ, จำกัด rate, ตอบ 200 แต่ 0 ไบต์) → หน้าเว็บขึ้นรูปแตกเป็นครั้งคราว
* การเก็บสำเนาไว้ใน `public/images/cinemas/` ทำให้เว็บไม่พึ่งโฮสต์เหล่านั้นอีก
*
* ใช้: node scripts/mirror-photos.mjs [--dry]
* --dry = ดาวน์โหลดและรายงานเฉย ๆ ไม่แก้ไฟล์
*
* ปลอดภัย: สำรอง content.json เป็น `content.json.bak-photos-<เวลา>` ก่อนเขียน
*/
import fs from "node:fs";
import path from "node:path";
const CONTENT_PATH = path.join("data", "content", "content.json");
const OUT_DIR = path.join("public", "images", "cinemas");
const PUBLIC_PREFIX = "/images/cinemas";
const MIN_BYTES = 2000;
const DELAY_MS = 900;
const RETRIES = 3;
const DRY = process.argv.includes("--dry");
const UA =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36";
const EXT_BY_TYPE = {
"image/jpeg": "jpg",
"image/jpg": "jpg",
"image/png": "png",
"image/webp": "webp",
"image/gif": "gif",
"image/avif": "avif",
};
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function download(url) {
for (let attempt = 1; attempt <= RETRIES; attempt++) {
try {
const res = await fetch(url, {
redirect: "follow",
headers: {
"user-agent": UA,
accept: "image/avif,image/webp,image/*,*/*;q=0.8",
"accept-language": "th,en;q=0.9",
},
signal: AbortSignal.timeout(25000),
});
const type = (res.headers.get("content-type") ?? "").split(";")[0].trim();
const buffer = Buffer.from(await res.arrayBuffer());
if (res.ok && type.startsWith("image/") && buffer.byteLength >= MIN_BYTES) {
return { ok: true, type, buffer, status: res.status };
}
if (attempt < RETRIES) await sleep(DELAY_MS * attempt);
} catch (error) {
if (attempt < RETRIES) await sleep(DELAY_MS * attempt);
if (attempt === RETRIES) return { ok: false, reason: error.message };
}
}
return { ok: false, reason: "ยังไม่ได้ไฟล์ที่ใช้ได้ (0 ไบต์ / 429 / ไม่ใช่รูป)" };
}
function slugifyName(value, fallback) {
const clean = String(value ?? "")
.toLowerCase()
.replace(/[^a-z0-9-]+/g, "-")
.replace(/^-+|-+$/g, "");
return clean === "" ? fallback : clean;
}
const raw = fs.readFileSync(CONTENT_PATH, "utf8");
const content = JSON.parse(raw);
fs.mkdirSync(OUT_DIR, { recursive: true });
const report = { saved: [], failed: [], skipped: 0 };
for (const cinema of content.cinemas ?? []) {
const photos = cinema.photos ?? [];
for (let index = 0; index < photos.length; index++) {
const url = photos[index];
if (!/^https?:\/\//i.test(url)) {
report.skipped++;
continue;
}
const result = await download(url);
if (!result.ok) {
report.failed.push({ slug: cinema.slug, index, reason: result.reason });
console.log(`พัง ${cinema.slug} #${index} — ${result.reason}`);
continue;
}
const ext = EXT_BY_TYPE[result.type] ?? "jpg";
const stem = slugifyName(cinema.slug, "cinema");
const fileName = photos.length > 1 ? `${stem}-${index + 1}.${ext}` : `${stem}.${ext}`;
const filePath = path.join(OUT_DIR, fileName);
const publicPath = `${PUBLIC_PREFIX}/${fileName}`;
if (!DRY) {
fs.writeFileSync(filePath, result.buffer);
photos[index] = publicPath;
}
report.saved.push({ slug: cinema.slug, index, publicPath, bytes: result.buffer.byteLength });
console.log(
`OK ${cinema.slug} #${index} → ${publicPath} (${Math.round(result.buffer.byteLength / 1024)} KB)`,
);
await sleep(DELAY_MS);
}
}
if (!DRY) {
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
fs.writeFileSync(`${CONTENT_PATH}.bak-photos-${stamp}`, raw);
fs.writeFileSync(CONTENT_PATH, `${JSON.stringify(content, null, 2)}\n`);
console.log(`\nสำรองข้อมูลเดิม: ${CONTENT_PATH}.bak-photos-${stamp}`);
}
console.log(`\nสรุป: บันทึก ${report.saved.length} · พัง ${report.failed.length} · ข้าม ${report.skipped}`);
if (report.failed.length > 0) {
console.log("รูปที่ยังพัง (หน้าเว็บจะแสดงโลโก้แทน): ");
for (const row of report.failed) console.log(` ${row.slug} #${row.index}`);
}