BlueGit

timfa filemanager

Files

filemanager / server / thumbnail-cache.js

thumbnail-cache.js

Cursor Optimisation pass
timfa Tim Falken · pushed by timfa · 5 months ago
7e6dfc52 History
thumbnail-cache.js 25.1 KiB Download Raw
1'use strict';
2
3const fs = require('fs');
4const path = require('path');
5const { spawn } = require('child_process');
6const sharp = require('sharp');
7
8const { loadConfig, getEffectivePaths } = require('./config');
9
10const PUBLIC_DIR = path.resolve(process.env.FILEMANAGER_PUBLIC_DIR || path.join(__dirname, '../public'));
11const THUMBS_DIR = path.resolve(process.env.FILEMANAGER_THUMBS_DIR || path.join(PUBLIC_DIR, 'thumbs'));
12const MANIFEST_PATH = path.join(THUMBS_DIR, '.manifest.json');
13const FOLDER_ICONS_PATH = path.join(THUMBS_DIR, '.folder-icons.json');
14const LOOP_DELAY_MS = toPositiveInt(process.env.THUMBNAIL_CACHE_LOOP_DELAY_MS, 15000);
15const ACTIVE_STREAM_LOOP_DELAY_MS = toPositiveInt(process.env.THUMBNAIL_CACHE_ACTIVE_STREAM_DELAY_MS, 120000);
16const THUMB_HTTP_MAX_AGE_SEC = toPositiveInt(process.env.THUMBNAIL_HTTP_MAX_AGE_SEC, 3600);
17
18const IMAGE_EXTS = new Set([
19 'jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'avif', 'svg', 'ico',
20]);
21const VIDEO_EXTS = new Set([
22 'mp4', 'mkv', 'mov', 'avi', 'webm', 'ogv', 'm4v', 'ts', 'mpeg', 'mpg',
23]);
24const MODEL_EXTS = new Set(['stl', 'obj']);
25
26let loopTimer = null;
27let loopStarted = false;
28let manifestCache = null;
29let manifestCacheMtimeMs = null;
30
31function toPosix (p)
32{
33 return String(p || '').split(path.sep).join('/');
34}
35
36function rootSegmentsForSourcePath (sourcePath)
37{
38 const resolved = path.resolve(sourcePath);
39 const stripped = resolved
40 .replace(/^\\+/, '')
41 .replace(/^\/+/, '')
42 .replace(/^([A-Za-z]):/, '$1');
43
44 return stripped
45 .split(/[\\/]+/)
46 .filter(Boolean)
47 .map(seg => seg.replace(/:/g, '_'));
48}
49
50function getThumbDirForSourceDir (sourceDir)
51{
52 return path.join(THUMBS_DIR, ...rootSegmentsForSourcePath(sourceDir));
53}
54
55function getThumbPathForSourceFile (sourceFile)
56{
57 const source = path.resolve(sourceFile);
58 return path.join(THUMBS_DIR, ...rootSegmentsForSourcePath(source)) + '.webp';
59}
60
61function getThumbRelPathForSourceFile (sourceFile)
62{
63 return toPosix(path.relative(PUBLIC_DIR, getThumbPathForSourceFile(sourceFile)));
64}
65
66function isImagePath (filePath)
67{
68 const ext = path.extname(filePath).slice(1).toLowerCase();
69 return IMAGE_EXTS.has(ext);
70}
71
72function isVideoPath (filePath)
73{
74 const ext = path.extname(filePath).slice(1).toLowerCase();
75 return VIDEO_EXTS.has(ext);
76}
77
78function isModelPath (filePath)
79{
80 const ext = path.extname(filePath).slice(1).toLowerCase();
81 return MODEL_EXTS.has(ext);
82}
83
84function ffmpegPath ()
85{
86 return String(process.env.FFMPEG_PATH || '').trim() || 'ffmpeg';
87}
88
89function ffprobePath ()
90{
91 return String(process.env.FFPROBE_PATH || '').trim() || 'ffprobe';
92}
93
94function runCommand (command, args)
95{
96 return new Promise((resolve, reject) =>
97 {
98 const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
99 let stdout = '';
100 let stderr = '';
101
102 child.stdout.on('data', (chunk) =>
103 {
104 stdout += chunk.toString();
105 });
106
107 child.stderr.on('data', (chunk) =>
108 {
109 stderr += chunk.toString();
110 });
111
112 child.on('error', (err) =>
113 {
114 if (err && err.code === 'ENOENT')
115 {
116 reject(new Error(`${command} is not installed or not available in PATH.`));
117 return;
118 }
119 reject(err);
120 });
121
122 child.on('close', (code) =>
123 {
124 if (code === 0)
125 {
126 resolve({ stdout, stderr });
127 return;
128 }
129 reject(new Error(stderr.trim() || `${command} exited with code ${code}.`));
130 });
131 });
132}
133
134function toPositiveInt (value, fallback)
135{
136 const parsed = Number.parseInt(String(value || ''), 10);
137 return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
138}
139
140function activeThumbnailLoopDelayMs ()
141{
142 try
143 {
144 const stream = require('./video-stream');
145 const count = Number(stream && typeof stream.getActiveStreamCount === 'function'
146 ? stream.getActiveStreamCount()
147 : 0);
148 if (Number.isFinite(count) && count > 0)
149 {
150 return Math.max(LOOP_DELAY_MS, ACTIVE_STREAM_LOOP_DELAY_MS);
151 }
152 }
153 catch
154 {
155 // Fallback to normal cadence if stream state is unavailable.
156 }
157
158 return LOOP_DELAY_MS;
159}
160
161async function probeDurationSeconds (sourceFile)
162{
163 const { stdout } = await runCommand(ffprobePath(), [
164 '-v', 'error',
165 '-print_format', 'json',
166 '-show_format',
167 sourceFile,
168 ]);
169
170 let payload;
171 try
172 {
173 payload = JSON.parse(stdout || '{}');
174 } catch
175 {
176 return null;
177 }
178
179 const duration = Number(payload && payload.format && payload.format.duration);
180 if (!Number.isFinite(duration) || duration <= 0) return null;
181 return duration;
182}
183
184async function exists (target)
185{
186 try
187 {
188 await fs.promises.access(target, fs.constants.F_OK);
189 return true;
190 } catch
191 {
192 return false;
193 }
194}
195
196async function ensureDir (dirPath)
197{
198 await fs.promises.mkdir(dirPath, { recursive: true });
199}
200
201async function readManifest ()
202{
203 try
204 {
205 const raw = await fs.promises.readFile(MANIFEST_PATH, 'utf8');
206 const parsed = JSON.parse(raw);
207 if (parsed && typeof parsed === 'object' && parsed.files && typeof parsed.files === 'object')
208 {
209 return parsed;
210 }
211 } catch
212 {
213 // Missing or malformed manifests are treated as empty.
214 }
215 return { version: 1, files: {} };
216}
217
218function invalidateManifestCache ()
219{
220 manifestCache = null;
221 manifestCacheMtimeMs = null;
222}
223
224async function readManifestCached ()
225{
226 try
227 {
228 const stat = await fs.promises.stat(MANIFEST_PATH);
229 if (manifestCache && manifestCacheMtimeMs === stat.mtimeMs)
230 {
231 return manifestCache;
232 }
233
234 const manifest = await readManifest();
235 manifestCache = manifest;
236 manifestCacheMtimeMs = stat.mtimeMs;
237 return manifest;
238 } catch
239 {
240 invalidateManifestCache();
241 return { version: 1, files: {} };
242 }
243}
244
245/**
246 * Returns a Set of source file paths that have a manifest entry (thumbnail expected).
247 */
248async function getThumbnailManifestSourcePathSet ()
249{
250 const manifest = await readManifestCached();
251 const paths = new Set();
252 for (const filePath of Object.keys(manifest.files || {}))
253 {
254 paths.add(path.resolve(filePath));
255 }
256 return paths;
257}
258
259async function writeManifest (manifest)
260{
261 const payload = JSON.stringify(manifest, null, 2);
262 const tmp = MANIFEST_PATH + '.tmp';
263 await fs.promises.writeFile(tmp, payload, 'utf8');
264 await fs.promises.rename(tmp, MANIFEST_PATH);
265 manifestCache = manifest;
266 try
267 {
268 manifestCacheMtimeMs = (await fs.promises.stat(MANIFEST_PATH)).mtimeMs;
269 } catch
270 {
271 invalidateManifestCache();
272 }
273}
274
275async function walkDir (dirPath, onDir, onFile)
276{
277 await onDir(dirPath);
278
279 let entries = [];
280 try
281 {
282 entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
283 } catch
284 {
285 return;
286 }
287
288 for (const entry of entries)
289 {
290 const full = path.join(dirPath, entry.name);
291 if (entry.isDirectory())
292 {
293 await walkDir(full, onDir, onFile);
294 continue;
295 }
296 if (entry.isFile())
297 {
298 await onFile(full);
299 }
300 }
301}
302
303async function removeFileIfExists (target)
304{
305 try
306 {
307 await fs.promises.unlink(target);
308 } catch (err)
309 {
310 if (err && err.code !== 'ENOENT') throw err;
311 }
312}
313
314async function pruneThumbTree (dirPath, keepFiles)
315{
316 let entries = [];
317 try
318 {
319 entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
320 } catch
321 {
322 return;
323 }
324
325 for (const entry of entries)
326 {
327 const full = path.join(dirPath, entry.name);
328 if (entry.isDirectory())
329 {
330 await pruneThumbTree(full, keepFiles);
331 continue;
332 }
333
334 if (full === MANIFEST_PATH || full === MANIFEST_PATH + '.tmp') continue;
335 if (full === FOLDER_ICONS_PATH || full === FOLDER_ICONS_PATH + '.tmp') continue;
336 if (!keepFiles.has(path.resolve(full)))
337 {
338 await removeFileIfExists(full);
339 }
340 }
341
342 // Never remove the root thumbs directory.
343 if (path.resolve(dirPath) === path.resolve(THUMBS_DIR)) return;
344
345 try
346 {
347 const leftovers = await fs.promises.readdir(dirPath);
348 if (leftovers.length === 0) await fs.promises.rmdir(dirPath);
349 } catch
350 {
351 // Ignore races while pruning.
352 }
353}
354
355async function generateImageThumb (sourceFile, thumbPath)
356{
357 await ensureDir(path.dirname(thumbPath));
358 await sharp(sourceFile)
359 .rotate()
360 .resize({ width: 99, height: 99, fit: 'inside', withoutEnlargement: true })
361 .webp({ quality: 80 })
362 .toFile(thumbPath);
363}
364
365async function generateVideoThumb (sourceFile, thumbPath)
366{
367 await ensureDir(path.dirname(thumbPath));
368
369 const duration = await probeDurationSeconds(sourceFile).catch(() => null);
370 let captureAt = 1;
371 if (duration && duration > 0)
372 {
373 captureAt = duration * 0.1;
374 if (duration > 0.2) captureAt = Math.min(captureAt, duration - 0.1);
375 captureAt = Math.max(0, captureAt);
376 }
377
378 const tmpPngPath = thumbPath + '.tmp.png';
379 try
380 {
381 await runCommand(ffmpegPath(), [
382 '-hide_banner',
383 '-loglevel', 'error',
384 '-y',
385 '-ss', captureAt.toFixed(3),
386 '-i', sourceFile,
387 '-frames:v', '1',
388 '-an',
389 '-sn',
390 tmpPngPath,
391 ]);
392
393 await sharp(tmpPngPath)
394 .rotate()
395 .resize({ width: 99, height: 99, fit: 'inside', withoutEnlargement: true })
396 .webp({ quality: 80 })
397 .toFile(thumbPath);
398 }
399 finally
400 {
401 await removeFileIfExists(tmpPngPath);
402 }
403}
404
405// ---------------------------------------------------------------------------
406// 3D model geometry parsing and thumbnail generation
407// ---------------------------------------------------------------------------
408
409function projectModelVector (v)
410{
411 const ry = Math.PI / 4;
412 const rx = -Math.PI / 5;
413 const x1 = v.x * Math.cos(ry) + v.z * Math.sin(ry);
414 const z1 = -v.x * Math.sin(ry) + v.z * Math.cos(ry);
415 const y2 = v.y * Math.cos(rx) - z1 * Math.sin(rx);
416 return { x: x1, y: y2, z: v.y * Math.sin(rx) + z1 * Math.cos(rx) };
417}
418
419function parseAsciiStlPolygons (text)
420{
421 const polygons = [];
422 const vertices = [];
423 const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
424 for (const lineRaw of lines)
425 {
426 const line = lineRaw.trim();
427 if (!/^vertex\s+/i.test(line)) continue;
428 const parts = line.split(/\s+/);
429 if (parts.length < 4) continue;
430 const x = Number(parts[1]);
431 const y = Number(parts[2]);
432 const z = Number(parts[3]);
433 if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))
434 {
435 vertices.push({ x, y, z });
436 }
437 }
438 for (let i = 0; i + 2 < vertices.length; i += 3)
439 {
440 polygons.push({ points: [vertices[i], vertices[i + 1], vertices[i + 2]] });
441 }
442 return polygons;
443}
444
445function parseBinaryStlPolygons (buf)
446{
447 const polygons = [];
448 if (!buf || buf.length < 84) return polygons;
449 const triCount = buf.readUInt32LE(80);
450 let offset = 84;
451 for (let i = 0; i < triCount; i++)
452 {
453 if (offset + 50 > buf.length) break;
454 offset += 12; // skip normal
455 const points = [];
456 for (let v = 0; v < 3; v++)
457 {
458 const x = buf.readFloatLE(offset);
459 const y = buf.readFloatLE(offset + 4);
460 const z = buf.readFloatLE(offset + 8);
461 points.push({ x, y, z });
462 offset += 12;
463 }
464 offset += 2; // attribute byte count
465 polygons.push({ points });
466 }
467 return polygons;
468}
469
470function resolveObjIndex (token, vertexCount)
471{
472 const raw = Number.parseInt(String(token || '').split('/')[0], 10);
473 if (!Number.isFinite(raw) || raw === 0) return null;
474 const index = raw < 0 ? vertexCount + raw : raw - 1;
475 if (index < 0 || index >= vertexCount) return null;
476 return index;
477}
478
479function parseObjPolygons (text)
480{
481 const vertices = [];
482 const faces = [];
483 const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
484 for (const lineRaw of lines)
485 {
486 const line = lineRaw.trim();
487 if (!line || line.startsWith('#')) continue;
488 if (/^v\s+/i.test(line))
489 {
490 const parts = line.split(/\s+/);
491 if (parts.length >= 4)
492 {
493 const x = Number(parts[1]);
494 const y = Number(parts[2]);
495 const z = Number(parts[3]);
496 if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))
497 {
498 vertices.push({ x, y, z });
499 }
500 }
501 }
502 else if (/^f\s+/i.test(line))
503 {
504 const parts = line.split(/\s+/).slice(1);
505 if (parts.length >= 3) faces.push(parts);
506 }
507 }
508 const polygons = [];
509 for (const face of faces)
510 {
511 const indices = face
512 .map((t) => resolveObjIndex(t, vertices.length))
513 .filter((i) => i != null);
514 if (indices.length < 3) continue;
515 const anchor = vertices[indices[0]];
516 for (let i = 1; i < indices.length - 1; i++)
517 {
518 const b = vertices[indices[i]];
519 const c = vertices[indices[i + 1]];
520 if (anchor && b && c) polygons.push({ points: [anchor, b, c] });
521 }
522 }
523 return polygons;
524}
525
526async function parseModelPolygons (sourceFile, ext)
527{
528 const buf = await fs.promises.readFile(sourceFile);
529 if (ext === 'obj') return parseObjPolygons(buf.toString('utf8'));
530 // STL: probe first 256 bytes for ASCII keyword
531 const probe = buf.toString('utf8', 0, Math.min(buf.length, 256));
532 if (/facet/i.test(probe)) return parseAsciiStlPolygons(buf.toString('utf8'));
533 return parseBinaryStlPolygons(buf);
534}
535
536function createModelSvgBuffer (polygons)
537{
538 const width = 160;
539 const height = 200;
540 const pad = 12;
541 let minX = Infinity;
542 let minY = Infinity;
543 let maxX = -Infinity;
544 let maxY = -Infinity;
545 for (const poly of polygons)
546 {
547 for (const pt of poly.points)
548 {
549 if (pt.x < minX) minX = pt.x;
550 if (pt.y < minY) minY = pt.y;
551 if (pt.x > maxX) maxX = pt.x;
552 if (pt.y > maxY) maxY = pt.y;
553 }
554 }
555 if (!Number.isFinite(minX)) return null;
556 const boxW = Math.max(1, maxX - minX);
557 const boxH = Math.max(1, maxY - minY);
558 const scale = Math.min((width - pad * 2) / boxW, (height - pad * 2 - 18) / boxH);
559 const cx = (minX + maxX) / 2;
560 const cy = (minY + maxY) / 2;
561 const svgPolys = polygons.map((poly) =>
562 {
563 const pts = poly.points.map((pt) =>
564 {
565 const x = width / 2 + (pt.x - cx) * scale;
566 const y = 18 + height / 2 + (pt.y - cy) * scale;
567 return `${x.toFixed(1)},${y.toFixed(1)}`;
568 }).join(' ');
569 return `<polygon points="${pts}" fill="rgba(47,109,255,0.28)" stroke="#7ea2ff" stroke-width="0.9" stroke-linejoin="round"/>`;
570 }).join('');
571 return Buffer.from(
572 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`
573 + `<defs><linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">`
574 + `<stop offset="0%" stop-color="#111826"/><stop offset="100%" stop-color="#0d111a"/>`
575 + `</linearGradient></defs>`
576 + `<rect width="${width}" height="${height}" rx="10" fill="url(#bg)"/>`
577 + `<rect x="0" y="0" width="${width}" height="28" fill="#2f6dff"/>`
578 + `<text x="80" y="17" font-family="sans-serif" font-size="12" text-anchor="middle" fill="#ffffff" font-weight="700">3D</text>`
579 + svgPolys
580 + `</svg>`,
581 'utf8',
582 );
583}
584
585async function generateModelThumb (sourceFile, thumbPath)
586{
587 const ext = path.extname(sourceFile).slice(1).toLowerCase();
588 const rawPolygons = await parseModelPolygons(sourceFile, ext);
589 if (!rawPolygons.length) throw new Error('No geometry found in model file');
590
591 const polygons = rawPolygons.map((poly) =>
592 {
593 const projected = poly.points.map(projectModelVector);
594 return {
595 points: projected.map((p) => ({ x: p.x, y: p.y })),
596 depth: projected.reduce((s, p) => s + p.z, 0) / projected.length,
597 };
598 });
599 polygons.sort((a, b) => a.depth - b.depth);
600
601 const svgBuf = createModelSvgBuffer(polygons);
602 if (!svgBuf) throw new Error('Failed to create SVG for model');
603
604 await ensureDir(path.dirname(thumbPath));
605 await sharp(svgBuf, { density: 144 })
606 .resize({ width: 99, height: 99, fit: 'inside', withoutEnlargement: true })
607 .webp({ quality: 80 })
608 .toFile(thumbPath);
609}
610
611function effectiveRoots ()
612{
613 const config = loadConfig();
614 const roots = getEffectivePaths(config.paths || []);
615
616 // Include the personal-user root tree so thumbnails are generated for
617 // files stored under userPath/<username>/... as well.
618 const userPath = typeof config.userPath === 'string' ? config.userPath.trim() : '';
619 if (userPath) roots.push(userPath);
620
621 // De-duplicate roots by resolved absolute path.
622 const seen = new Set();
623 const deduped = [];
624 for (const root of roots)
625 {
626 const key = path.resolve(root);
627 if (seen.has(key)) continue;
628 seen.add(key);
629 deduped.push(root);
630 }
631
632 return deduped;
633}
634
635function pathInsideOrEqualResolved (targetPath, rootPath)
636{
637 const rel = path.relative(path.resolve(rootPath), path.resolve(targetPath));
638 return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
639}
640
641function preserveRootFromPreviousManifest (rootPath, prevManifest, nextManifest, keepThumbFiles)
642{
643 for (const [sourcePath, meta] of Object.entries(prevManifest.files || {}))
644 {
645 if (!pathInsideOrEqualResolved(sourcePath, rootPath)) continue;
646 nextManifest.files[sourcePath] = meta;
647 if (meta && meta.thumbRelPath)
648 {
649 keepThumbFiles.add(path.resolve(path.join(PUBLIC_DIR, meta.thumbRelPath)));
650 }
651 }
652}
653
654async function syncThumbnailCacheOnce ()
655{
656 await ensureDir(THUMBS_DIR);
657
658 const prevManifest = await readManifest();
659 const nextManifest = { version: 1, files: {} };
660 const keepThumbFiles = new Set();
661 const roots = effectiveRoots();
662
663 for (const root of roots)
664 {
665 const resolvedRoot = path.resolve(root);
666 if (!(await exists(resolvedRoot)))
667 {
668 // Keep prior cache for roots that are temporarily offline (e.g. removable mounts).
669 preserveRootFromPreviousManifest(resolvedRoot, prevManifest, nextManifest, keepThumbFiles);
670 continue;
671 }
672
673 try
674 {
675 const stat = await fs.promises.stat(resolvedRoot);
676 if (!stat.isDirectory())
677 {
678 preserveRootFromPreviousManifest(resolvedRoot, prevManifest, nextManifest, keepThumbFiles);
679 continue;
680 }
681 // Probe readability; failures should not wipe existing cache state.
682 await fs.promises.readdir(resolvedRoot);
683 }
684 catch
685 {
686 preserveRootFromPreviousManifest(resolvedRoot, prevManifest, nextManifest, keepThumbFiles);
687 continue;
688 }
689
690 await walkDir(
691 resolvedRoot,
692 async (dirPath) =>
693 {
694 await ensureDir(getThumbDirForSourceDir(dirPath));
695 },
696 async (filePath) =>
697 {
698 const kind = isImagePath(filePath)
699 ? 'image'
700 : isVideoPath(filePath)
701 ? 'video'
702 : isModelPath(filePath)
703 ? 'model'
704 : null;
705 if (!kind) return;
706
707 let stat;
708 try
709 {
710 stat = await fs.promises.stat(filePath);
711 } catch
712 {
713 return;
714 }
715
716 const thumbPath = getThumbPathForSourceFile(filePath);
717 const thumbRelPath = getThumbRelPathForSourceFile(filePath);
718 keepThumbFiles.add(path.resolve(thumbPath));
719
720 const prev = prevManifest.files[filePath];
721 const unchangedByStat =
722 prev &&
723 Number(prev.size) === Number(stat.size) &&
724 Number(prev.mtimeMs) === Number(stat.mtimeMs) &&
725 prev.thumbRelPath === thumbRelPath &&
726 (prev.kind === kind || !prev.kind);
727
728 if (unchangedByStat && await exists(thumbPath))
729 {
730 nextManifest.files[filePath] = {
731 ...prev,
732 kind,
733 };
734 return;
735 }
736
737 if (kind === 'image')
738 {
739 if (!unchangedByStat || !(await exists(thumbPath)))
740 {
741 try
742 {
743 await generateImageThumb(filePath, thumbPath);
744 } catch
745 {
746 return;
747 }
748 }
749
750 nextManifest.files[filePath] = {
751 sha256: prev && prev.sha256 ? prev.sha256 : null,
752 size: stat.size,
753 mtimeMs: stat.mtimeMs,
754 thumbRelPath,
755 kind,
756 };
757 return;
758 }
759
760 if (kind === 'video')
761 {
762 try
763 {
764 await generateVideoThumb(filePath, thumbPath);
765 } catch
766 {
767 return;
768 }
769
770 nextManifest.files[filePath] = {
771 sha256: null,
772 size: stat.size,
773 mtimeMs: stat.mtimeMs,
774 thumbRelPath,
775 kind,
776 };
777 return;
778 }
779
780 // kind === 'model'
781 try
782 {
783 await generateModelThumb(filePath, thumbPath);
784 } catch
785 {
786 return;
787 }
788
789 nextManifest.files[filePath] = {
790 sha256: null,
791 size: stat.size,
792 mtimeMs: stat.mtimeMs,
793 thumbRelPath,
794 kind,
795 };
796 },
797 );
798 }
799
800 for (const [sourcePath, oldMeta] of Object.entries(prevManifest.files || {}))
801 {
802 if (nextManifest.files[sourcePath]) continue;
803 const oldThumbRel = oldMeta && oldMeta.thumbRelPath;
804 if (!oldThumbRel) continue;
805 const oldThumbPath = path.resolve(path.join(PUBLIC_DIR, oldThumbRel));
806 await removeFileIfExists(oldThumbPath);
807 }
808
809 await pruneThumbTree(THUMBS_DIR, keepThumbFiles);
810 await writeManifest(nextManifest);
811
812 return {
813 rootsScanned: roots.length,
814 cachedCount: Object.keys(nextManifest.files).length,
815 };
816}
817
818function scheduleNextRun (delayMs)
819{
820 loopTimer = setTimeout(async () =>
821 {
822 loopTimer = null;
823 try
824 {
825 await syncThumbnailCacheOnce();
826 }
827 catch (err)
828 {
829 console.error('[thumb-cache] sync failed:', err && err.message ? err.message : err);
830 }
831 finally
832 {
833 if (loopStarted) scheduleNextRun(activeThumbnailLoopDelayMs());
834 }
835 }, delayMs);
836
837 if (loopTimer && typeof loopTimer.unref === 'function') loopTimer.unref();
838}
839
840function startThumbnailCacheLoop ()
841{
842 if (loopStarted) return;
843 loopStarted = true;
844 scheduleNextRun(activeThumbnailLoopDelayMs());
845}
846
847function stopThumbnailCacheLoop ()
848{
849 loopStarted = false;
850 if (loopTimer)
851 {
852 clearTimeout(loopTimer);
853 loopTimer = null;
854 }
855}
856
857async function getCachedThumbnailInfo (sourceFile)
858{
859 const thumbPath = getThumbPathForSourceFile(sourceFile);
860 if (!(await exists(thumbPath))) return null;
861 return {
862 thumbPath,
863 contentType: 'image/webp',
864 };
865}
866
867// ---------------------------------------------------------------------------
868// Folder icon assignments — stored in .folder-icons.json
869// ---------------------------------------------------------------------------
870
871async function readFolderIcons ()
872{
873 try
874 {
875 const raw = await fs.promises.readFile(FOLDER_ICONS_PATH, 'utf8');
876 const parsed = JSON.parse(raw);
877 if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
878 } catch
879 {
880 // Missing or malformed — treat as empty.
881 }
882 return {};
883}
884
885async function writeFolderIcons (obj)
886{
887 await ensureDir(THUMBS_DIR);
888 const payload = JSON.stringify(obj, null, 2);
889 const tmp = FOLDER_ICONS_PATH + '.tmp';
890 await fs.promises.writeFile(tmp, payload, 'utf8');
891 await fs.promises.rename(tmp, FOLDER_ICONS_PATH);
892}
893
894/**
895 * Returns all files inside `dirPath` (recursive) that have a cached thumbnail,
896 * sorted lexicographically by absolute file path.
897 * Each element: { filePath: string, thumbRelPath: string }
898 */
899async function getFilesWithThumbnailsInDir (dirPath)
900{
901 const manifest = await readManifestCached();
902 const resolved = path.resolve(dirPath);
903 const prefix = resolved + path.sep;
904 const results = [];
905
906 for (const [filePath, meta] of Object.entries(manifest.files || {}))
907 {
908 if (!meta || !meta.thumbRelPath) continue;
909
910 const resolvedFile = path.resolve(filePath);
911 if (resolvedFile !== resolved && !resolvedFile.startsWith(prefix)) continue;
912
913 results.push({ filePath, thumbRelPath: meta.thumbRelPath });
914 }
915
916 results.sort((a, b) => a.filePath.localeCompare(b.filePath));
917 return results;
918}
919
920// Backward-compatible alias used by existing imports/tests.
921async function getImagesWithThumbnailsInDir (dirPath)
922{
923 return getFilesWithThumbnailsInDir(dirPath);
924}
925
926/**
927 * Returns the source file path used as the icon for `folderPath`.
928 * Looks up the explicit assignment first; falls back to the first cached image found.
929 * Returns null when no files with cached thumbnails exist inside the folder.
930 */
931async function getFolderIconSourceFile (folderPath)
932{
933 const resolved = path.resolve(folderPath);
934 const icons = await readFolderIcons();
935
936 if (icons[resolved])
937 {
938 const assigned = icons[resolved];
939 // Verify the assigned image still has a cached thumbnail.
940 const thumbPath = getThumbPathForSourceFile(assigned);
941 if (await exists(thumbPath)) return assigned;
942 // Stale — fall through to auto-detect.
943 }
944
945 // Auto: first cached image inside the folder.
946 const files = await getFilesWithThumbnailsInDir(folderPath);
947 return files.length ? files[0].filePath : null;
948}
949
950/**
951 * Saves an explicit folder icon assignment.
952 * Pass `imagePath = null` to clear the explicit assignment (auto-detect will be used instead).
953 */
954async function setFolderIconAssignment (folderPath, imagePath)
955{
956 const resolved = path.resolve(folderPath);
957 const icons = await readFolderIcons();
958
959 if (imagePath === null || imagePath === undefined)
960 {
961 delete icons[resolved];
962 } else
963 {
964 icons[resolved] = imagePath;
965 }
966
967 await writeFolderIcons(icons);
968}
969
970module.exports = {
971 getCachedThumbnailInfo,
972 getThumbPathForSourceFile,
973 getThumbRelPathForSourceFile,
974 getThumbnailManifestSourcePathSet,
975 getFilesWithThumbnailsInDir,
976 getImagesWithThumbnailsInDir,
977 getFolderIconSourceFile,
978 setFolderIconAssignment,
979 startThumbnailCacheLoop,
980 stopThumbnailCacheLoop,
981 syncThumbnailCacheOnce,
982 THUMB_HTTP_MAX_AGE_SEC,
983};