1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
| 'use strict' /** * 相册批量生成器 v2(全盘扫描版 · 跨平台可移植) * * 用法: MEDIA_ROOT=G:\ node _album_gen.js(默认媒体根 G:\,可用环境变量 MEDIA_ROOT 覆盖) * * 结构: * 相册首页 source/相册/index.md —— 按年份分组(2008→2026 + 其他) * source/相册/<顶层文件夹名>/index.md —— 每个顶层文件夹一个相册页 */
const fs = require('fs') const path = require('path')
const MEDIA_ROOT = process.env.MEDIA_ROOT || 'G:\\' const SRC_ALBUM = path.join(__dirname, 'source', '相册') const DATE = '2026-09-14'
const IMG_EXT = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.heic', '.tif', '.tiff', '.jfif'] const VID_EXT = ['.mp4', '.mov', '.avi', '.mkv', '.wmv', '.flv', '.m4v', '.webm', '.ts', '.3gp']
function enc (s) { return encodeURIComponent(s) } function safeDir (s) { return s.replace(/[\\/:*?"<>|]/g, '_') }
function relToUrl (rel) { return '/media/' + rel.split(/[\\/]/).map(enc).join('/') }
function thumbRel (rel) { return '_thumbs/' + rel.replace(/\.[^.]+$/, '') + '.jpg' }
function imgUrl (rel) { if (fs.existsSync(path.join(MEDIA_ROOT, thumbRel(rel)))) return relToUrl(thumbRel(rel)) return relToUrl(rel) }
// ===== 视频截帧(ffmpeg)===== function findFfmpeg () { try { const p = require('ffmpeg-static'); if (p && fs.existsSync(p)) return p } catch (e) {} try { const r = require('child_process').execSync('where ffmpeg', { encoding: 'utf8', stdio: 'pipe' }) const p = r.trim().split(/\r?\n/)[0].trim() if (p && fs.existsSync(p)) return p } catch (e) {} try { const r = require('child_process').execSync('which ffmpeg', { encoding: 'utf8', stdio: 'pipe' }) const p = r.trim().split(/\r?\n/)[0].trim() if (p && fs.existsSync(p)) return p } catch (e) {} const local = path.join(__dirname, 'bin', 'ffmpeg.exe') if (fs.existsSync(local)) return local return null } const FFMPEG = findFfmpeg() const VIDEO_COVER_DIR = '_video_covers'
function extractVideoFrame (videoAbs, albumName, seekSec) { if (!FFMPEG) return null const base = path.basename(videoAbs, path.extname(videoAbs)) const outRel = `${VIDEO_COVER_DIR}/${safeDir(albumName)}/${base}.jpg` const outAbs = path.join(MEDIA_ROOT, outRel) if (fs.existsSync(outAbs)) return outRel fs.mkdirSync(path.dirname(outAbs), { recursive: true }) try { let fsize = 0 try { fsize = fs.statSync(videoAbs).size } catch (e) {} const isBig = fsize > 100 * 1024 * 1024 const args = isBig ? ['-y', '-ss', '0.1', '-noaccurate_seek', '-i', videoAbs, '-frames:v', '1', '-q:v', '8', '-vf', 'scale=320:-1', outAbs] : ['-y', '-ss', String(seekSec || 1), '-noaccurate_seek', '-i', videoAbs, '-frames:v', '1', '-q:v', '5', '-vf', 'scale=640:-1', outAbs] require('child_process').execFileSync(FFMPEG, args, { stdio: 'pipe' }) return fs.existsSync(outAbs) ? outRel : null } catch (e) { return null } }
function findVideoByName (vids, name) { if (!name) return null const target = String(name).toLowerCase() let m = vids.find(v => v.rel.toLowerCase() === target) if (m) return m m = vids.find(v => v.name.toLowerCase() === path.basename(target).toLowerCase()) return m || null }
function collect (dirAbs, recursive) { const imgs = [] const vids = [] function walkDir (d) { let entries try { entries = fs.readdirSync(d, { withFileTypes: true }) } catch (e) { return } for (const e of entries) { const full = path.join(d, e.name) if (e.isDirectory()) { if (recursive) walkDir(full) } else if (e.isFile()) { const ext = path.extname(e.name).toLowerCase() let size = 0 try { size = fs.statSync(full).size } catch (e2) {} const rel = path.relative(MEDIA_ROOT, full).split(path.sep).join('/') const item = { name: e.name, size, rel } if (IMG_EXT.includes(ext)) imgs.push(item) else if (VID_EXT.includes(ext)) vids.push(item) } } } walkDir(dirAbs) imgs.sort((a, b) => a.name.localeCompare(b.name, 'zh')) vids.sort((a, b) => a.name.localeCompare(b.name, 'zh')) return { imgs, vids } }
function altOf (name) { const base = path.basename(name, path.extname(name)) return base.replace(/[[\]()]/g, '').trim() || name }
function galleryMarkdown (imgs) { if (!imgs.length) return '' const lines = imgs.map(i => `})`) return '{% gallery %}\n' + lines.join('\n') + '\n{% endgallery %}' }
function videoMarkdown (vids) { if (!vids.length) return '' const lines = vids.map(v => { const albumName = v.rel.split('/')[0] const coverRel = extractVideoFrame(path.join(MEDIA_ROOT, v.rel), albumName, 1) const poster = coverRel ? relToUrl(coverRel) : '' return `<video controls preload="metadata" poster="${poster}" style="width:100%;margin:6px 0;" src="${relToUrl(v.rel)}"></video>` }) return '#### 视频记录\n\n' + lines.join('\n') }
function loadCovers () { const f = path.join(__dirname, '_covers.json') try { return JSON.parse(fs.readFileSync(f, 'utf8')) } catch (e) { return {} } }
function loadProtected () { const f = path.join(__dirname, '_protected.json') try { return JSON.parse(fs.readFileSync(f, 'utf8')) } catch (e) { return {} } }
function findCoverByName (imgs, name) { if (!name) return null const target = String(name).toLowerCase() let m = imgs.find(i => i.rel.toLowerCase() === target) if (m) return m m = imgs.find(i => i.name.toLowerCase() === path.basename(target).toLowerCase()) return m || null }
function scanAlbums () { let topsRaw = [] try { topsRaw = fs.readdirSync(MEDIA_ROOT, { withFileTypes: true }) } catch (e) { console.error('无法读取媒体根目录: ' + MEDIA_ROOT, e.message); process.exit(1) } const tops = topsRaw .filter(d => d.isDirectory()) .map(d => d.name) .filter(n => !n.startsWith('$') && n !== 'System Volume Information' && n !== 'RECYCLE.BIN' && !n.startsWith('_')) .sort((a, b) => a.localeCompare(b, 'zh')) const albums = [] const covers = loadCovers() const protSet = loadProtected() for (const name of tops) { const topAbs = path.join(MEDIA_ROOT, name) const sections = [] const root = collect(topAbs, false) let subRaw = [] try { subRaw = fs.readdirSync(topAbs, { withFileTypes: true }) } catch (e) {} const subDirs = subRaw .filter(d => d.isDirectory()) .map(d => d.name) .sort((a, b) => a.localeCompare(b, 'zh')) if (root.imgs.length || root.vids.length) sections.push({ title: '根目录', ...root }) for (const sd of subDirs) { const c = collect(path.join(topAbs, sd), true) if (c.imgs.length || c.vids.length) sections.push({ title: sd, ...c }) } const allImgs = sections.reduce((a, s) => a.concat(s.imgs), []) const allVids = sections.reduce((a, s) => a.concat(s.vids), []) let cover = null const custom = covers[name] if (custom && String(custom).startsWith('video:')) { const spec = String(custom).slice(6) const at = spec.indexOf('@') const vidName = at >= 0 ? spec.slice(0, at) : spec const ts = at >= 0 ? parseFloat(spec.slice(at + 1)) : 1 const vid = findVideoByName(allVids, vidName) if (vid) { const fr = extractVideoFrame(path.join(MEDIA_ROOT, vid.rel), name, ts) if (fr) cover = { rel: fr, name: path.basename(fr), abs: path.join(MEDIA_ROOT, fr), fromVideo: true } } else { console.log(' 警告: 相册「' + name + '」指定的视频 "' + vidName + '" 未找到') } } else if (custom) { cover = findCoverByName(allImgs, custom) if (!cover) console.log(' 警告: 相册「' + name + '」指定的封面 "' + custom + '" 未找到,回退用最大图') } if (!cover) cover = allImgs.slice().sort((a, b) => b.size - a.size)[0] || null if (!cover && allVids.length) { const fr = extractVideoFrame(path.join(MEDIA_ROOT, allVids[0].rel), name, 1) if (fr) cover = { rel: fr, name: path.basename(fr), abs: path.join(MEDIA_ROOT, fr), fromVideo: true } else cover = { defaultVideo: true, url: '/images/video-cover.svg' } } albums.push({ name, sections, imgs: allImgs, vids: allVids, cover }) } return albums }
function yearOf (name) { const m = /^(\d{4})/.exec(name) return m ? m[1] : '其他' }
function displayTitle (name) { return name.replace(/^(\d{4})-/, '$1 · ') }
function descrOf (a) { const parts = [] if (a.imgs.length) parts.push(a.imgs.length + ' 张照片') if (a.vids.length) parts.push(a.vids.length + ' 视频') return parts.join(' + ') }
// 把封面图复制到 source/相册/covers/(博客静态目录),返回静态 URL // 相册首页封面不走 /media/,不受相册密码拦截;点进相册页才需要密码 function prepareCover (a) { if (!a.cover) return null if (a.cover.defaultVideo || a.cover.defaultPrivate) return a.cover.url const coverDir = path.join(SRC_ALBUM, 'covers') const destName = safeDir(a.name) + '.jpg' const destAbs = path.join(coverDir, destName) try { const thumb = path.join(MEDIA_ROOT, thumbRel(a.cover.rel)) const srcAbs = fs.existsSync(thumb) ? thumb : path.join(MEDIA_ROOT, a.cover.rel) fs.mkdirSync(coverDir, { recursive: true }) fs.copyFileSync(srcAbs, destAbs) return '/相册/covers/' + destName } catch (e) { console.log(' 警告: 复制封面失败「' + a.name + '」→ ' + e.message) return imgUrl(a.cover.rel) } }
function buildIndex (albums) { const groups = {} for (const a of albums) { const y = yearOf(a.name) ;(groups[y] = groups[y] || []).push(a) } const years = Object.keys(groups).filter(y => y !== '其他').sort() if (groups['其他']) years.push('其他') const out = [] out.push('---') out.push('title: 相册') out.push('date: ' + DATE) out.push('top_img: false') out.push('comments: false') out.push('---') out.push('') out.push('<div class="note note-primary"><p>有些光,要慢慢拾;有些回忆,要轻轻翻。</p></div>') out.push('') for (const y of years) { out.push('## ' + y) out.push('') out.push('<div class="gallery-group-main">') for (const a of groups[y]) { const coverUrl = prepareCover(a) if (!coverUrl) { console.log(' 跳过无封面相册: ' + a.name); continue } out.push(`{% galleryGroup '${displayTitle(a.name)}' '${descrOf(a)}' '/相册/${enc(a.name)}' '${coverUrl}' %}`) } out.push('</div>') out.push('') } return out.join('\n') }
function buildAlbumPage (a) { const out = [] out.push('---') out.push('title: ' + displayTitle(a.name)) out.push('date: ' + DATE) out.push('top_img: false') out.push('comments: false') out.push('---') out.push('') out.push(`<div class="note note-primary"><p>${displayTitle(a.name)} · 共 ${descrOf(a)},点击可放大 / 播放。</p></div>`) out.push('') for (const s of a.sections) { if (a.sections.length > 1) { out.push('## ' + s.title) out.push('') } const g = galleryMarkdown(s.imgs) if (g) { out.push(g); out.push('') } const v = videoMarkdown(s.vids) if (v) { out.push(v); out.push('') } } return out.join('\n') }
function main () { fs.rmSync(SRC_ALBUM, { recursive: true, force: true }) fs.mkdirSync(SRC_ALBUM, { recursive: true })
const albums = scanAlbums()
fs.writeFileSync(path.join(SRC_ALBUM, 'index.md'), buildIndex(albums), 'utf8')
for (const a of albums) { const dir = path.join(SRC_ALBUM, safeDir(a.name)) fs.mkdirSync(dir, { recursive: true }) fs.writeFileSync(path.join(dir, 'index.md'), buildAlbumPage(a), 'utf8') }
let tImg = 0, tVid = 0 for (const a of albums) { tImg += a.imgs.length; tVid += a.vids.length } console.log('生成完成:') console.log(' 相册首页: source/相册/index.md') console.log(' 相册详情页: ' + albums.length + ' 个') console.log(' 合计照片 ' + tImg + ' 张,视频 ' + tVid + ' 段') }
main()
|