'use strict'; const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const sharp = require('sharp'); const { loadConfig, getEffectivePaths } = require('./config'); const PUBLIC_DIR = path.resolve(process.env.FILEMANAGER_PUBLIC_DIR || path.join(__dirname, '../public')); const THUMBS_DIR = path.resolve(process.env.FILEMANAGER_THUMBS_DIR || path.join(PUBLIC_DIR, 'thumbs')); const MANIFEST_PATH = path.join(THUMBS_DIR, '.manifest.json'); const LOOP_DELAY_MS = 5000; const IMAGE_EXTS = new Set([ 'jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'avif', ]); let loopTimer = null; let loopStarted = false; function toPosix (p) { return String(p || '').split(path.sep).join('/'); } function rootSegmentsForSourcePath (sourcePath) { const resolved = path.resolve(sourcePath); const stripped = resolved .replace(/^\\+/, '') .replace(/^\/+/, '') .replace(/^([A-Za-z]):/, '$1'); return stripped .split(/[\\/]+/) .filter(Boolean) .map(seg => seg.replace(/:/g, '_')); } function getThumbDirForSourceDir (sourceDir) { return path.join(THUMBS_DIR, ...rootSegmentsForSourcePath(sourceDir)); } function getThumbPathForSourceFile (sourceFile) { const source = path.resolve(sourceFile); return path.join(THUMBS_DIR, ...rootSegmentsForSourcePath(source)) + '.webp'; } function getThumbRelPathForSourceFile (sourceFile) { return toPosix(path.relative(PUBLIC_DIR, getThumbPathForSourceFile(sourceFile))); } function isImagePath (filePath) { const ext = path.extname(filePath).slice(1).toLowerCase(); return IMAGE_EXTS.has(ext); } async function exists (target) { try { await fs.promises.access(target, fs.constants.F_OK); return true; } catch { return false; } } async function ensureDir (dirPath) { await fs.promises.mkdir(dirPath, { recursive: true }); } async function readManifest () { try { const raw = await fs.promises.readFile(MANIFEST_PATH, 'utf8'); const parsed = JSON.parse(raw); if (parsed && typeof parsed === 'object' && parsed.files && typeof parsed.files === 'object') { return parsed; } } catch { // Missing or malformed manifests are treated as empty. } return { version: 1, files: {} }; } async function writeManifest (manifest) { const payload = JSON.stringify(manifest, null, 2); const tmp = MANIFEST_PATH + '.tmp'; await fs.promises.writeFile(tmp, payload, 'utf8'); await fs.promises.rename(tmp, MANIFEST_PATH); } function sha256File (target) { return new Promise((resolve, reject) => { const hash = crypto.createHash('sha256'); const stream = fs.createReadStream(target); stream.on('error', reject); stream.on('data', chunk => hash.update(chunk)); stream.on('end', () => resolve(hash.digest('hex'))); }); } async function walkDir (dirPath, onDir, onFile) { await onDir(dirPath); let entries = []; try { entries = await fs.promises.readdir(dirPath, { withFileTypes: true }); } catch { return; } for (const entry of entries) { const full = path.join(dirPath, entry.name); if (entry.isDirectory()) { await walkDir(full, onDir, onFile); continue; } if (entry.isFile()) { await onFile(full); } } } async function removeFileIfExists (target) { try { await fs.promises.unlink(target); } catch (err) { if (err && err.code !== 'ENOENT') throw err; } } async function pruneThumbTree (dirPath, keepFiles) { let entries = []; try { entries = await fs.promises.readdir(dirPath, { withFileTypes: true }); } catch { return; } for (const entry of entries) { const full = path.join(dirPath, entry.name); if (entry.isDirectory()) { await pruneThumbTree(full, keepFiles); continue; } if (full === MANIFEST_PATH || full === MANIFEST_PATH + '.tmp') continue; if (!keepFiles.has(path.resolve(full))) { await removeFileIfExists(full); } } // Never remove the root thumbs directory. if (path.resolve(dirPath) === path.resolve(THUMBS_DIR)) return; try { const leftovers = await fs.promises.readdir(dirPath); if (leftovers.length === 0) await fs.promises.rmdir(dirPath); } catch { // Ignore races while pruning. } } async function generateImageThumb (sourceFile, thumbPath) { await ensureDir(path.dirname(thumbPath)); await sharp(sourceFile) .rotate() .resize({ width: 99, height: 99, fit: 'inside', withoutEnlargement: true }) .webp({ quality: 80 }) .toFile(thumbPath); } function effectiveRoots () { return getEffectivePaths(loadConfig().paths || []); } async function syncThumbnailCacheOnce () { await ensureDir(THUMBS_DIR); const prevManifest = await readManifest(); const nextManifest = { version: 1, files: {} }; const keepThumbFiles = new Set(); const roots = effectiveRoots(); for (const root of roots) { const resolvedRoot = path.resolve(root); if (!(await exists(resolvedRoot))) continue; await walkDir( resolvedRoot, async (dirPath) => { await ensureDir(getThumbDirForSourceDir(dirPath)); }, async (filePath) => { if (!isImagePath(filePath)) return; let stat; try { stat = await fs.promises.stat(filePath); } catch { return; } const thumbPath = getThumbPathForSourceFile(filePath); const thumbRelPath = getThumbRelPathForSourceFile(filePath); keepThumbFiles.add(path.resolve(thumbPath)); const prev = prevManifest.files[filePath]; const unchangedByStat = prev && Number(prev.size) === Number(stat.size) && Number(prev.mtimeMs) === Number(stat.mtimeMs) && prev.thumbRelPath === thumbRelPath; if (unchangedByStat && await exists(thumbPath)) { nextManifest.files[filePath] = prev; return; } let sha256; try { sha256 = await sha256File(filePath); } catch { return; } const unchangedByHash = prev && prev.sha256 === sha256 && await exists(thumbPath); if (!unchangedByHash) { try { await generateImageThumb(filePath, thumbPath); } catch { return; } } nextManifest.files[filePath] = { sha256, size: stat.size, mtimeMs: stat.mtimeMs, thumbRelPath, }; }, ); } for (const [sourcePath, oldMeta] of Object.entries(prevManifest.files || {})) { if (nextManifest.files[sourcePath]) continue; const oldThumbRel = oldMeta && oldMeta.thumbRelPath; if (!oldThumbRel) continue; const oldThumbPath = path.resolve(path.join(PUBLIC_DIR, oldThumbRel)); await removeFileIfExists(oldThumbPath); } await pruneThumbTree(THUMBS_DIR, keepThumbFiles); await writeManifest(nextManifest); return { rootsScanned: roots.length, cachedCount: Object.keys(nextManifest.files).length, }; } function scheduleNextRun (delayMs) { loopTimer = setTimeout(async () => { loopTimer = null; try { await syncThumbnailCacheOnce(); } catch (err) { console.error('[thumb-cache] sync failed:', err && err.message ? err.message : err); } finally { if (loopStarted) scheduleNextRun(LOOP_DELAY_MS); } }, delayMs); if (loopTimer && typeof loopTimer.unref === 'function') loopTimer.unref(); } function startThumbnailCacheLoop () { if (loopStarted) return; loopStarted = true; scheduleNextRun(LOOP_DELAY_MS); } function stopThumbnailCacheLoop () { loopStarted = false; if (loopTimer) { clearTimeout(loopTimer); loopTimer = null; } } async function getCachedThumbnailInfo (sourceFile) { const thumbPath = getThumbPathForSourceFile(sourceFile); if (!(await exists(thumbPath))) return null; return { thumbPath, contentType: 'image/webp', }; } module.exports = { getCachedThumbnailInfo, getThumbPathForSourceFile, getThumbRelPathForSourceFile, startThumbnailCacheLoop, stopThumbnailCacheLoop, syncThumbnailCacheOnce, };