BlueGit

timfa filemanager

Files

filemanager / server / thumbnail-cache.js

thumbnail-cache.js

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