#!/usr/bin/env node /** * sync_images_to_storage.mjs — อัปโหลดรูปจากเครื่องนี้เข้า SeaweedFS (core_management) * แล้วบันทึกแถวในตาราง public.images * * ที่มา: frontend/public/image/{stations,routes,stops,qrcode} * - stations/. → entity_type=station, entity_id=, kind=photo * - routes// → entity_type=route, entity_id= (qr ถ้าชื่อมี qr) * - stops/. → entity_type=stop, entity_id= * - qrcode/. → entity_type=route, entity_id=, kind=qr * * ปลายทาง: PUT /buckets/transit/// * url_path = /// (backend เสิร์ฟผ่าน /files/) * * ใช้: node script/sync_images_to_storage.mjs [--apply] [--limit N] * env: STORAGE_URL (default http://103.107.52.82:3103), PGHOST/PGPORT/PGUSER/PGPASSWORD/PGDATABASE */ import fs from "node:fs"; import path from "node:path"; import crypto from "node:crypto"; import { createRequire } from "node:module"; const require = createRequire(process.cwd() + "/package.json"); const { Client } = require("pg"); const ROOT = process.env.IMAGE_DIR || "D:/Git/workspace/web-at-transit/frontend/public/image"; const STORAGE = (process.env.STORAGE_URL || "http://103.107.52.82:3103").replace(/\/$/, ""); const BUCKET = "/buckets/transit"; const args = process.argv.slice(2); const APPLY = args.includes("--apply"); const LIMIT = (() => { const i = args.indexOf("--limit"); return i > -1 ? Number(args[i + 1]) : 0; })(); const EXT_OK = new Set([".jpg", ".jpeg", ".png", ".webp"]); const SKIP_DIRS = new Set(["icons", "partners", "network", "landmarks", "extras", "_original"]); const MIME = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp" }; function collect() { const out = []; for (const area of fs.readdirSync(ROOT)) { if (SKIP_DIRS.has(area)) continue; const areaDir = path.join(ROOT, area); if (!fs.statSync(areaDir).isDirectory()) continue; for (const entry of fs.readdirSync(areaDir)) { const full = path.join(areaDir, entry); const stat = fs.statSync(full); let files = []; let entityId; let type; if (stat.isDirectory()) { if (area !== "routes") continue; type = "route"; entityId = entry; files = fs.readdirSync(full).map((f) => path.join(full, f)); } else { if (area === "stations") type = "station"; // schema ไม่รองรับ entity_type=stop (CHECK อนุญาต route/station/sponsor/province/bus/misc) else if (area === "stops") continue; else if (area === "qrcode") type = "route"; else continue; entityId = path.basename(entry, path.extname(entry)); files = [full]; } for (const f of files) { const ext = path.extname(f).toLowerCase(); if (!EXT_OK.has(ext)) continue; const name = path.basename(f); // kind ที่ CHECK ยอมรับ: photo | logo | icon | map | hero const kind = "photo"; out.push({ file: f, ext, type, entityId, kind, name }); } } } return out; } async function main() { let items = collect(); if (LIMIT) items = items.slice(0, LIMIT); console.log(`images: ${items.length} ไฟล์ (apply=${APPLY}) storage=${STORAGE}`); const client = new Client({ host: process.env.PGHOST, port: Number(process.env.PGPORT || 5432), user: process.env.PGUSER, password: process.env.PGPASSWORD, database: process.env.PGDATABASE, connectionTimeoutMillis: 8000, }); await client.connect(); let uploaded = 0; let skipped = 0; let failed = 0; for (const it of items) { const urlPath = `/${it.type}/${it.entityId}/${it.name}`; const fid = `${BUCKET}${urlPath}`; const exists = await client.query("select 1 from public.images where url_path = $1 limit 1", [urlPath]); if (exists.rowCount) { skipped++; continue; } if (!APPLY) { console.log(`[dry-run] ${it.type}/${it.entityId} ${it.name} (${it.kind})`); continue; } const buf = fs.readFileSync(it.file); try { const res = await fetch(`${STORAGE}${fid}`, { method: "PUT", headers: { "Content-Type": MIME[it.ext] || "application/octet-stream" }, body: buf, }); if (!res.ok) throw new Error(`storage ${res.status}`); const sha = crypto.createHash("sha256").update(buf).digest("hex"); await client.query( `insert into public.images (id, entity_type, entity_id, kind, fid, url_path, display_order, meta) values ($1,$2,$3,$4,$5,$6,0,$7::jsonb)`, [ crypto.randomUUID(), it.type, String(it.entityId), it.kind, fid, urlPath, JSON.stringify({ mime: MIME[it.ext], size_bytes: buf.length, sha256: sha }), ], ); uploaded++; console.log(`[ok] ${urlPath}`); } catch (e) { failed++; console.error(`[fail] ${urlPath}: ${e.message}`); } } console.log(JSON.stringify({ uploaded, skipped, failed, total: items.length })); await client.end(); } main().catch((e) => { console.error("FAILED:", e.code || "", e.message); process.exit(1); });