BlueGit

timfa filemanager

Files

filemanager / server / thumbnail-cache.js

thumbnail-cache.js

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