chris 0e4461e957 fix: reseed sets createdAt from filename timestamp or file mtime
Photos reseeded from disk now sort by their original upload time
instead of all getting the same insertion timestamp.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 11:29:11 -04:00

75 lines
2.4 KiB
JavaScript

#!/usr/bin/env node
/**
* Re-seed Photo documents from existing uploads when Mongo data is lost.
* - One doc per webp file on disk.
* - Captions default to filename without suffix.
* - Tags default to ['uncategorized'] unless a prefix is present.
* - Variants NOT linked; each file is its own doc.
*
* Usage: node scripts/reseed_uploads.js
* Make sure MONGO_URI is set (or uses default).
*/
const fs = require('fs');
const path = require('path');
const mongoose = require('mongoose');
const Photo = require('../models/photo');
const MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost:27017/photogallery';
const UPLOAD_DIR = path.join(__dirname, '..', 'uploads');
const VARIANT_SUFFIXES = {
'': 'main',
'-md': 'medium',
'-sm': 'thumb'
};
function parseFilename(file) {
const ext = path.extname(file);
const base = path.basename(file, ext);
const matched = base.match(/(.+?)(-md|-sm)?$/);
if (!matched) return { baseName: base, variant: 'main', ext };
const baseName = matched[1];
const variant = VARIANT_SUFFIXES[matched[2] || ''] || 'main';
return { baseName, variant, ext };
}
async function main() {
await mongoose.connect(MONGO_URI);
console.log('Connected to Mongo:', MONGO_URI);
const files = fs.readdirSync(UPLOAD_DIR).filter(f => {
const lower = f.toLowerCase();
return lower.endsWith('.webp') && !lower.endsWith('-sm.webp') && !lower.endsWith('-md.webp');
});
let created = 0;
for (const file of files) {
const existing = await Photo.findOne({ filename: file });
if (existing) continue;
const baseName = path.basename(file, path.extname(file));
const caption = baseName.replace(/[-_]+/g, ' ');
const tag = baseName.split('-')[1] || 'uncategorized';
const tsMatch = file.match(/^(\d{13})-/);
const createdAt = tsMatch
? new Date(parseInt(tsMatch[1]))
: fs.statSync(path.join(UPLOAD_DIR, file)).mtime;
const doc = new Photo({
filename: file,
path: path.join('uploads', file),
caption,
tags: [tag],
createdAt,
updatedAt: createdAt,
});
await doc.save();
created++;
}
console.log(`Seed complete. Created ${created} photo documents.`);
await mongoose.disconnect();
}
main().catch(err => {
console.error(err);
process.exit(1);
});