'use strict'; const fs = require('fs'); const os = require('os'); const path = require('path'); const sharp = require('sharp'); sharp.cache(false); let mockPaths = []; jest.mock('../server/config', () => ({ loadConfig: () => ({ paths: [...mockPaths] }), getEffectivePaths: (paths) => paths, })); async function writeTinyPng (target) { await sharp({ create: { width: 400, height: 240, channels: 3, background: { r: 120, g: 180, b: 220 }, }, }).png().toFile(target); } function writeTinySvg (target) { const svg = ` `; fs.writeFileSync(target, svg, 'utf8'); } function writeExecutable (target, content) { fs.writeFileSync(target, content, { encoding: 'utf8', mode: 0o755 }); fs.chmodSync(target, 0o755); } describe('thumbnail cache worker', () => { let tempDir; let publicDir; let thumbsDir; let sourceRoot; function loadModule () { jest.resetModules(); return require('../server/thumbnail-cache'); } beforeEach(() => { tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-thumb-cache-')); publicDir = path.join(tempDir, 'public'); thumbsDir = path.join(publicDir, 'thumbs'); sourceRoot = path.join(tempDir, 'root'); fs.mkdirSync(publicDir, { recursive: true }); fs.mkdirSync(sourceRoot, { recursive: true }); process.env.FILEMANAGER_PUBLIC_DIR = publicDir; process.env.FILEMANAGER_THUMBS_DIR = thumbsDir; mockPaths = [sourceRoot]; }); afterEach(() => { delete process.env.FILEMANAGER_PUBLIC_DIR; delete process.env.FILEMANAGER_THUMBS_DIR; delete process.env.FFMPEG_PATH; delete process.env.FFPROBE_PATH; mockPaths = []; try { fs.rmSync(tempDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 30 }); } catch (err) { if (!err || !/EBUSY|EPERM/i.test(String(err.code || err.message || ''))) { throw err; } } }); test('creates cached thumbnail with dimensions smaller than 100px', async () => { const mod = loadModule(); const imagePath = path.join(sourceRoot, 'photos', 'sample.png'); fs.mkdirSync(path.dirname(imagePath), { recursive: true }); await writeTinyPng(imagePath); await mod.syncThumbnailCacheOnce(); const thumbPath = mod.getThumbPathForSourceFile(imagePath); expect(fs.existsSync(thumbPath)).toBe(true); const meta = await sharp(thumbPath).metadata(); expect(meta.width).toBeLessThan(100); expect(meta.height).toBeLessThan(100); const manifestPath = path.join(thumbsDir, '.manifest.json'); const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); expect(manifest.files[imagePath]).toBeTruthy(); }); test('removes cached thumbnail when source file is deleted', async () => { const mod = loadModule(); const imagePath = path.join(sourceRoot, 'sample.png'); await writeTinyPng(imagePath); await mod.syncThumbnailCacheOnce(); const thumbPath = mod.getThumbPathForSourceFile(imagePath); expect(fs.existsSync(thumbPath)).toBe(true); fs.unlinkSync(imagePath); await mod.syncThumbnailCacheOnce(); expect(fs.existsSync(thumbPath)).toBe(false); }); test('preserves folder-icons.json across sync cycles', async () => { const mod = loadModule(); // Run one sync to create the thumbs dir. await mod.syncThumbnailCacheOnce(); // Write a folder icon assignment directly. await mod.setFolderIconAssignment(sourceRoot, path.join(sourceRoot, 'cover.jpg')); const iconsPath = path.join(thumbsDir, '.folder-icons.json'); expect(fs.existsSync(iconsPath)).toBe(true); // Run sync again — the file must survive pruning. await mod.syncThumbnailCacheOnce(); expect(fs.existsSync(iconsPath)).toBe(true); const stored = JSON.parse(fs.readFileSync(iconsPath, 'utf8')); expect(stored[path.resolve(sourceRoot)]).toBe(path.join(sourceRoot, 'cover.jpg')); }); test('creates cached thumbnail for svg files', async () => { const mod = loadModule(); const imagePath = path.join(sourceRoot, 'assets', 'logo.svg'); fs.mkdirSync(path.dirname(imagePath), { recursive: true }); writeTinySvg(imagePath); await mod.syncThumbnailCacheOnce(); const thumbPath = mod.getThumbPathForSourceFile(imagePath); expect(fs.existsSync(thumbPath)).toBe(true); const info = await mod.getCachedThumbnailInfo(imagePath); expect(info).toBeTruthy(); expect(info.thumbPath).toBe(thumbPath); }); test('auto-detects first cached image inside /public-style root', async () => { const mod = loadModule(); const publicRoot = path.join(tempDir, 'public-root'); fs.mkdirSync(publicRoot, { recursive: true }); mockPaths = [publicRoot]; const nested = path.join(publicRoot, 'icons', 'a.svg'); fs.mkdirSync(path.dirname(nested), { recursive: true }); writeTinySvg(nested); await mod.syncThumbnailCacheOnce(); const detected = await mod.getFolderIconSourceFile(publicRoot); expect(detected).toBe(nested); }); test('preserves assigned folder icon and thumbnail when root is temporarily unavailable', async () => { const mod = loadModule(); const imagePath = path.join(sourceRoot, 'Pepijn', 'cover.jpg'); fs.mkdirSync(path.dirname(imagePath), { recursive: true }); await writeTinyPng(imagePath); await mod.syncThumbnailCacheOnce(); await mod.setFolderIconAssignment(path.dirname(imagePath), imagePath); const thumbPath = mod.getThumbPathForSourceFile(imagePath); expect(fs.existsSync(thumbPath)).toBe(true); expect(await mod.getFolderIconSourceFile(path.dirname(imagePath))).toBe(imagePath); // Simulate mount disappearing while still configured. const offlinePath = sourceRoot + '-offline'; fs.renameSync(sourceRoot, offlinePath); await mod.syncThumbnailCacheOnce(); // Cache entry and assignment must survive the temporary outage. expect(fs.existsSync(thumbPath)).toBe(true); expect(await mod.getFolderIconSourceFile(path.dirname(imagePath))).toBe(imagePath); fs.renameSync(offlinePath, sourceRoot); }); test('creates cached thumbnail for video files using ffmpeg frame extraction', async () => { const mod = loadModule(); const toolsDir = path.join(tempDir, 'tools'); const ffprobeScript = path.join(toolsDir, 'ffprobe-mock.js'); const ffmpegScript = path.join(toolsDir, 'ffmpeg-mock.js'); const ffmpegArgsLog = path.join(tempDir, 'ffmpeg-args.log'); const sourceFramePng = path.join(tempDir, 'ffmpeg-source-frame.png'); fs.mkdirSync(toolsDir, { recursive: true }); await writeTinyPng(sourceFramePng); writeExecutable(ffprobeScript, `#!/usr/bin/env node\nprocess.stdout.write(JSON.stringify({ format: { duration: '20' } }));\n`); writeExecutable(ffmpegScript, `#!/usr/bin/env node\nconst fs = require('fs');\nconst args = process.argv.slice(2);\nfs.writeFileSync(${JSON.stringify(ffmpegArgsLog)}, args.join('\\n'), 'utf8');\nconst outPath = args[args.length - 1];\nfs.copyFileSync(${JSON.stringify(sourceFramePng)}, outPath);\n`); process.env.FFPROBE_PATH = ffprobeScript; process.env.FFMPEG_PATH = ffmpegScript; const videoPath = path.join(sourceRoot, 'clips', 'sample.mp4'); fs.mkdirSync(path.dirname(videoPath), { recursive: true }); fs.writeFileSync(videoPath, 'fake-video-data'); await mod.syncThumbnailCacheOnce(); const thumbPath = mod.getThumbPathForSourceFile(videoPath); expect(fs.existsSync(thumbPath)).toBe(true); const info = await mod.getCachedThumbnailInfo(videoPath); expect(info).toBeTruthy(); expect(info.thumbPath).toBe(thumbPath); const ffmpegArgs = fs.readFileSync(ffmpegArgsLog, 'utf8'); expect(ffmpegArgs).toContain('-ss'); expect(ffmpegArgs).toContain('2.000'); }); test('creates cached thumbnail for STL model files using server-side geometry projection', async () => { const mod = loadModule(); const stlContent = [ 'solid test', 'facet normal 0 0 1', ' outer loop', ' vertex 0 0 0', ' vertex 1 0 0', ' vertex 0 1 0', ' endloop', 'endfacet', 'endsolid test', ].join('\n'); const modelPath = path.join(sourceRoot, 'models', 'part.stl'); fs.mkdirSync(path.dirname(modelPath), { recursive: true }); fs.writeFileSync(modelPath, stlContent, 'utf8'); await mod.syncThumbnailCacheOnce(); const thumbPath = mod.getThumbPathForSourceFile(modelPath); expect(fs.existsSync(thumbPath)).toBe(true); const meta = await sharp(thumbPath).metadata(); expect(meta.format).toBe('webp'); expect(meta.width).toBeLessThanOrEqual(99); expect(meta.height).toBeLessThanOrEqual(99); const info = await mod.getCachedThumbnailInfo(modelPath); expect(info).toBeTruthy(); expect(info.thumbPath).toBe(thumbPath); }); });