BlueGit

timfa filemanager

Files

filemanager / tests / thumbnail-cache.test.js

thumbnail-cache.test.js

thumbnail-cache.test.js 9.0 KiB Download Raw
1'use strict';
2
3const fs = require('fs');
4const os = require('os');
5const path = require('path');
6const sharp = require('sharp');
7
8sharp.cache(false);
9
10let mockPaths = [];
11
12jest.mock('../server/config', () => ({
13 loadConfig: () => ({ paths: [...mockPaths] }),
14 getEffectivePaths: (paths) => paths,
15}));
16
17async function writeTinyPng (target)
18{
19 await sharp({
20 create: {
21 width: 400,
22 height: 240,
23 channels: 3,
24 background: { r: 120, g: 180, b: 220 },
25 },
26 }).png().toFile(target);
27}
28
29function writeTinySvg (target)
30{
31 const svg = `<?xml version="1.0" encoding="UTF-8"?>
32<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120" viewBox="0 0 200 120">
33 <rect x="0" y="0" width="200" height="120" fill="#2a7fff"/>
34 <circle cx="60" cy="60" r="32" fill="#ffd166"/>
35 <rect x="105" y="30" width="70" height="60" rx="10" fill="#0f172a"/>
36</svg>`;
37 fs.writeFileSync(target, svg, 'utf8');
38}
39
40function writeExecutable (target, content)
41{
42 fs.writeFileSync(target, content, { encoding: 'utf8', mode: 0o755 });
43 fs.chmodSync(target, 0o755);
44}
45
46describe('thumbnail cache worker', () =>
47{
48 let tempDir;
49 let publicDir;
50 let thumbsDir;
51 let sourceRoot;
52
53 function loadModule ()
54 {
55 jest.resetModules();
56 return require('../server/thumbnail-cache');
57 }
58
59 beforeEach(() =>
60 {
61 tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-thumb-cache-'));
62 publicDir = path.join(tempDir, 'public');
63 thumbsDir = path.join(publicDir, 'thumbs');
64 sourceRoot = path.join(tempDir, 'root');
65
66 fs.mkdirSync(publicDir, { recursive: true });
67 fs.mkdirSync(sourceRoot, { recursive: true });
68
69 process.env.FILEMANAGER_PUBLIC_DIR = publicDir;
70 process.env.FILEMANAGER_THUMBS_DIR = thumbsDir;
71 mockPaths = [sourceRoot];
72 });
73
74 afterEach(() =>
75 {
76 delete process.env.FILEMANAGER_PUBLIC_DIR;
77 delete process.env.FILEMANAGER_THUMBS_DIR;
78 delete process.env.FFMPEG_PATH;
79 delete process.env.FFPROBE_PATH;
80 mockPaths = [];
81 try
82 {
83 fs.rmSync(tempDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 30 });
84 } catch (err)
85 {
86 if (!err || !/EBUSY|EPERM/i.test(String(err.code || err.message || '')))
87 {
88 throw err;
89 }
90 }
91 });
92
93 test('creates cached thumbnail with dimensions smaller than 100px', async () =>
94 {
95 const mod = loadModule();
96 const imagePath = path.join(sourceRoot, 'photos', 'sample.png');
97 fs.mkdirSync(path.dirname(imagePath), { recursive: true });
98 await writeTinyPng(imagePath);
99
100 await mod.syncThumbnailCacheOnce();
101
102 const thumbPath = mod.getThumbPathForSourceFile(imagePath);
103 expect(fs.existsSync(thumbPath)).toBe(true);
104
105 const meta = await sharp(thumbPath).metadata();
106 expect(meta.width).toBeLessThan(100);
107 expect(meta.height).toBeLessThan(100);
108
109 const manifestPath = path.join(thumbsDir, '.manifest.json');
110 const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
111 expect(manifest.files[imagePath]).toBeTruthy();
112 });
113
114 test('removes cached thumbnail when source file is deleted', async () =>
115 {
116 const mod = loadModule();
117 const imagePath = path.join(sourceRoot, 'sample.png');
118 await writeTinyPng(imagePath);
119
120 await mod.syncThumbnailCacheOnce();
121 const thumbPath = mod.getThumbPathForSourceFile(imagePath);
122 expect(fs.existsSync(thumbPath)).toBe(true);
123
124 fs.unlinkSync(imagePath);
125 await mod.syncThumbnailCacheOnce();
126
127 expect(fs.existsSync(thumbPath)).toBe(false);
128 });
129
130 test('preserves folder-icons.json across sync cycles', async () =>
131 {
132 const mod = loadModule();
133
134 // Run one sync to create the thumbs dir.
135 await mod.syncThumbnailCacheOnce();
136
137 // Write a folder icon assignment directly.
138 await mod.setFolderIconAssignment(sourceRoot, path.join(sourceRoot, 'cover.jpg'));
139
140 const iconsPath = path.join(thumbsDir, '.folder-icons.json');
141 expect(fs.existsSync(iconsPath)).toBe(true);
142
143 // Run sync again — the file must survive pruning.
144 await mod.syncThumbnailCacheOnce();
145
146 expect(fs.existsSync(iconsPath)).toBe(true);
147 const stored = JSON.parse(fs.readFileSync(iconsPath, 'utf8'));
148 expect(stored[path.resolve(sourceRoot)]).toBe(path.join(sourceRoot, 'cover.jpg'));
149 });
150
151 test('creates cached thumbnail for svg files', async () =>
152 {
153 const mod = loadModule();
154 const imagePath = path.join(sourceRoot, 'assets', 'logo.svg');
155 fs.mkdirSync(path.dirname(imagePath), { recursive: true });
156 writeTinySvg(imagePath);
157
158 await mod.syncThumbnailCacheOnce();
159
160 const thumbPath = mod.getThumbPathForSourceFile(imagePath);
161 expect(fs.existsSync(thumbPath)).toBe(true);
162
163 const info = await mod.getCachedThumbnailInfo(imagePath);
164 expect(info).toBeTruthy();
165 expect(info.thumbPath).toBe(thumbPath);
166 });
167
168 test('auto-detects first cached image inside /public-style root', async () =>
169 {
170 const mod = loadModule();
171 const publicRoot = path.join(tempDir, 'public-root');
172 fs.mkdirSync(publicRoot, { recursive: true });
173 mockPaths = [publicRoot];
174
175 const nested = path.join(publicRoot, 'icons', 'a.svg');
176 fs.mkdirSync(path.dirname(nested), { recursive: true });
177 writeTinySvg(nested);
178
179 await mod.syncThumbnailCacheOnce();
180
181 const detected = await mod.getFolderIconSourceFile(publicRoot);
182 expect(detected).toBe(nested);
183 });
184
185 test('preserves assigned folder icon and thumbnail when root is temporarily unavailable', async () =>
186 {
187 const mod = loadModule();
188 const imagePath = path.join(sourceRoot, 'Pepijn', 'cover.jpg');
189 fs.mkdirSync(path.dirname(imagePath), { recursive: true });
190 await writeTinyPng(imagePath);
191
192 await mod.syncThumbnailCacheOnce();
193 await mod.setFolderIconAssignment(path.dirname(imagePath), imagePath);
194
195 const thumbPath = mod.getThumbPathForSourceFile(imagePath);
196 expect(fs.existsSync(thumbPath)).toBe(true);
197 expect(await mod.getFolderIconSourceFile(path.dirname(imagePath))).toBe(imagePath);
198
199 // Simulate mount disappearing while still configured.
200 const offlinePath = sourceRoot + '-offline';
201 fs.renameSync(sourceRoot, offlinePath);
202
203 await mod.syncThumbnailCacheOnce();
204
205 // Cache entry and assignment must survive the temporary outage.
206 expect(fs.existsSync(thumbPath)).toBe(true);
207 expect(await mod.getFolderIconSourceFile(path.dirname(imagePath))).toBe(imagePath);
208
209 fs.renameSync(offlinePath, sourceRoot);
210 });
211
212 test('creates cached thumbnail for video files using ffmpeg frame extraction', async () =>
213 {
214 const mod = loadModule();
215 const toolsDir = path.join(tempDir, 'tools');
216 const ffprobeScript = path.join(toolsDir, 'ffprobe-mock.js');
217 const ffmpegScript = path.join(toolsDir, 'ffmpeg-mock.js');
218 const ffmpegArgsLog = path.join(tempDir, 'ffmpeg-args.log');
219 const sourceFramePng = path.join(tempDir, 'ffmpeg-source-frame.png');
220
221 fs.mkdirSync(toolsDir, { recursive: true });
222 await writeTinyPng(sourceFramePng);
223
224 writeExecutable(ffprobeScript, `#!/usr/bin/env node\nprocess.stdout.write(JSON.stringify({ format: { duration: '20' } }));\n`);
225 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`);
226
227 process.env.FFPROBE_PATH = ffprobeScript;
228 process.env.FFMPEG_PATH = ffmpegScript;
229
230 const videoPath = path.join(sourceRoot, 'clips', 'sample.mp4');
231 fs.mkdirSync(path.dirname(videoPath), { recursive: true });
232 fs.writeFileSync(videoPath, 'fake-video-data');
233
234 await mod.syncThumbnailCacheOnce();
235
236 const thumbPath = mod.getThumbPathForSourceFile(videoPath);
237 expect(fs.existsSync(thumbPath)).toBe(true);
238
239 const info = await mod.getCachedThumbnailInfo(videoPath);
240 expect(info).toBeTruthy();
241 expect(info.thumbPath).toBe(thumbPath);
242
243 const ffmpegArgs = fs.readFileSync(ffmpegArgsLog, 'utf8');
244 expect(ffmpegArgs).toContain('-ss');
245 expect(ffmpegArgs).toContain('2.000');
246 });
247
248 test('creates cached thumbnail for STL model files using server-side geometry projection', async () =>
249 {
250 const mod = loadModule();
251
252 const stlContent = [
253 'solid test',
254 'facet normal 0 0 1',
255 ' outer loop',
256 ' vertex 0 0 0',
257 ' vertex 1 0 0',
258 ' vertex 0 1 0',
259 ' endloop',
260 'endfacet',
261 'endsolid test',
262 ].join('\n');
263
264 const modelPath = path.join(sourceRoot, 'models', 'part.stl');
265 fs.mkdirSync(path.dirname(modelPath), { recursive: true });
266 fs.writeFileSync(modelPath, stlContent, 'utf8');
267
268 await mod.syncThumbnailCacheOnce();
269
270 const thumbPath = mod.getThumbPathForSourceFile(modelPath);
271 expect(fs.existsSync(thumbPath)).toBe(true);
272
273 const meta = await sharp(thumbPath).metadata();
274 expect(meta.format).toBe('webp');
275 expect(meta.width).toBeLessThanOrEqual(99);
276 expect(meta.height).toBeLessThanOrEqual(99);
277
278 const info = await mod.getCachedThumbnailInfo(modelPath);
279 expect(info).toBeTruthy();
280 expect(info.thumbPath).toBe(thumbPath);
281 });
282});