/** * # 脚本 下载缺失媒体文件(media 表行存在但 public/uploads 无物理文件的) * 配合 import-live-posts.ts:dump 快照之后新上传的图片需从原站拉取。 * 用法:bun scripts/download-missing-media.ts */ import { SQL } from "bun"; import { existsSync, mkdirSync } from "node:fs"; import { dirname, join } from "node:path"; const LIVE = "https://www.dusuniot.com"; const sql = new SQL(process.env.DATABASE_URL || "postgres://dusuniot:dusuniot@127.0.0.1:25432/dusuniot", { max: 1 }); const rows = await sql`select id, path, url from media order by id`; let ok = 0, fail = 0; for (const r of rows) { const f = join("public", "uploads", r.path); if (existsSync(f)) continue; const res = await fetch(`${LIVE}/wp-content/uploads/${r.path}`, { headers: { "User-Agent": "Mozilla/5.0" } }); if (!res.ok) { console.log("MISS", res.status, r.path); fail++; continue; } mkdirSync(dirname(f), { recursive: true }); await Bun.write(f, res); ok++; if (ok % 20 === 0) console.log(`... ${ok} downloaded`); } console.log("下载完成:", ok, "缺失:", fail); await sql.end();