BlueGit

timfa filemanager

Files

filemanager / server / thumbnail-cache.js

thumbnail-cache.js

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