125 lines
4.0 KiB
JavaScript
125 lines
4.0 KiB
JavaScript
const fs = require('fs');
|
|
const path = require('path');
|
|
const { execFile } = require('child_process');
|
|
const { db, upsertVideo, deleteVideosByPaths, THUMB_DIR } = require('./db');
|
|
|
|
const VIDEO_EXTS = new Set(['.mp4', '.mkv', '.webm', '.mov', '.avi', '.m4v', '.mpg', '.mpeg', '.ts', '.wmv']);
|
|
|
|
function walkDir(dir, base = dir) {
|
|
const results = [];
|
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
const full = path.join(dir, entry.name);
|
|
if (entry.isDirectory()) {
|
|
results.push(...walkDir(full, base));
|
|
} else if (entry.isFile() && VIDEO_EXTS.has(path.extname(entry.name).toLowerCase())) {
|
|
const rel = path.relative(base, full);
|
|
results.push({ absPath: full, relPath: rel, filename: entry.name });
|
|
}
|
|
}
|
|
return results;
|
|
}
|
|
|
|
function channelOf(relPath) {
|
|
const parts = relPath.split(path.sep);
|
|
if (parts.length <= 1) return 'Uncategorized';
|
|
return parts[0];
|
|
}
|
|
|
|
function titleOf(filename) {
|
|
const base = filename.replace(/\.[^.]+$/, '');
|
|
return base.replace(/[._-]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
}
|
|
|
|
function probeDuration(absPath) {
|
|
return new Promise((resolve) => {
|
|
execFile('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', absPath],
|
|
{ timeout: 30000 }, (err, stdout) => {
|
|
const d = parseFloat(String(stdout || '').trim());
|
|
resolve(isFinite(d) && d > 0 ? d : 0);
|
|
});
|
|
});
|
|
}
|
|
|
|
function makeThumbnail(id, absPath, duration) {
|
|
const thumbPath = path.join(THUMB_DIR, `${id}.jpg`);
|
|
const seek = duration > 0 ? Math.min(Math.max(duration * 0.25, 0.5), 10) : 1;
|
|
return new Promise((resolve) => {
|
|
execFile('ffmpeg', ['-y', '-ss', String(seek), '-i', absPath, '-frames:v', '1', '-vf', 'scale=640:-2', thumbPath],
|
|
{ timeout: 30000 }, (err) => {
|
|
if (err) {
|
|
try { fs.unlinkSync(thumbPath); } catch {}
|
|
resolve(null);
|
|
} else {
|
|
resolve(thumbPath);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
async function rescan(rootDir, { onProgress } = {}) {
|
|
const files = walkDir(rootDir);
|
|
const seen = new Set();
|
|
let added = 0, updated = 0, unchanged = 0, failed = 0;
|
|
|
|
for (const f of files) {
|
|
seen.add(f.relPath);
|
|
let stat;
|
|
try {
|
|
stat = fs.statSync(f.absPath);
|
|
} catch {
|
|
failed++;
|
|
continue;
|
|
}
|
|
const existing = db.prepare('SELECT * FROM videos WHERE path = ?').get(f.relPath);
|
|
if (existing && Math.abs(existing.size - stat.size) < 1 && Math.abs(existing.mtime - stat.mtimeMs / 1000) < 1) {
|
|
unchanged++;
|
|
continue;
|
|
}
|
|
const duration = await probeDuration(f.absPath);
|
|
if (!duration) failed++;
|
|
const channel = channelOf(f.relPath);
|
|
const title = titleOf(f.filename);
|
|
const isNew = !existing;
|
|
const id = upsertVideo({
|
|
path: f.relPath,
|
|
filename: f.filename,
|
|
title,
|
|
channel,
|
|
duration,
|
|
size: stat.size,
|
|
mtime: stat.mtimeMs / 1000,
|
|
});
|
|
if (isNew) added++; else updated++;
|
|
const thumbPath = path.join(THUMB_DIR, `${id}.jpg`);
|
|
if (!fs.existsSync(thumbPath) || isNew) {
|
|
await makeThumbnail(id, f.absPath, duration);
|
|
}
|
|
if (onProgress) onProgress({ done: added + updated + unchanged, total: files.length });
|
|
}
|
|
|
|
const stale = db.prepare('SELECT id, path FROM videos').all().filter(r => !seen.has(r.path));
|
|
if (stale.length) {
|
|
deleteVideosByPaths(stale.map(r => r.path));
|
|
for (const r of stale) {
|
|
try { fs.unlinkSync(path.join(THUMB_DIR, `${r.id}.jpg`)); } catch {}
|
|
}
|
|
}
|
|
|
|
return { total: files.length, added, updated, unchanged, failed, removed: stale.length };
|
|
}
|
|
|
|
if (require.main === module) {
|
|
const rootDir = process.argv[2] || path.join(__dirname, '..', 'demo-videos');
|
|
rescan(rootDir, { onProgress: p => process.stdout.write(`\rscanned ${p.done}/${p.total}`) })
|
|
.then(stats => {
|
|
console.log('\nRescan complete:', stats);
|
|
process.exit(0);
|
|
})
|
|
.catch(err => {
|
|
console.error('Scan failed:', err);
|
|
process.exit(1);
|
|
});
|
|
}
|
|
|
|
module.exports = { rescan, walkDir, channelOf, titleOf };
|