BlueGit

timfa filemanager

Add fuzzy file search and global favicon APIs

timfa Tim Falken · pushed by timfa

Authored 2026-05-17 · 6 months ago

Hash
6b698edc169b4d8237cdf28b8ab1efaa36904370
Parent
69553149
2 files changed +319 −1
server/routes/files.js +236 −0
@@ -211,6 +211,138 @@ function isAccessiblePath (absPath, roots, user, config)
211 211 return resolveRootForUser(absPath, roots, user, config) !== null;
212 212 }
213 213
214 function readableSearchRootsForUser (user, config, roots)
215 {
216 const out = [];
217 for (const root of roots)
218 {
219 const label = path.basename(root);
220 if (canRead(user, label)) out.push(root);
221 }
222
223 const personal = getUserFolderPath(config, user && user.username);
224 if (personal) out.push(personal);
225
226 // Deduplicate by resolved path.
227 const seen = new Set();
228 return out.filter((p) =>
229 {
230 const key = path.resolve(p);
231 if (seen.has(key)) return false;
232 seen.add(key);
233 return true;
234 });
235 }
236
237 function fuzzyMatchScore (needle, haystack)
238 {
239 const q = String(needle || '').trim().toLowerCase();
240 const t = String(haystack || '').toLowerCase();
241 if (!q || !t) return null;
242
243 // Strong boost for contiguous substring matches.
244 const idx = t.indexOf(q);
245 if (idx >= 0)
246 {
247 const compactBonus = Math.max(0, 200 - idx);
248 const lengthBonus = Math.max(0, 120 - (t.length - q.length));
249 return 1200 + compactBonus + lengthBonus;
250 }
251
252 // Fallback: subsequence fuzzy match.
253 let qPos = 0;
254 let firstHit = -1;
255 let lastHit = -1;
256 let gaps = 0;
257
258 for (let i = 0; i < t.length && qPos < q.length; i++)
259 {
260 if (t[i] !== q[qPos]) continue;
261 if (firstHit === -1) firstHit = i;
262 if (lastHit >= 0) gaps += Math.max(0, i - lastHit - 1);
263 lastHit = i;
264 qPos += 1;
265 }
266
267 if (qPos !== q.length) return null;
268
269 const span = lastHit - firstHit + 1;
270 const compactness = Math.max(0, 300 - span);
271 const gapPenalty = Math.min(180, gaps * 3);
272 const startBonus = Math.max(0, 120 - firstHit);
273 return 700 + compactness + startBonus - gapPenalty;
274 }
275
276 function searchFilesInRoots (query, roots, maxResults)
277 {
278 const limit = Math.max(1, Math.min(500, Number(maxResults) || 200));
279 const results = [];
280 const visitedDirs = new Set();
281
282 for (const root of roots)
283 {
284 const rootPath = path.resolve(root);
285 const stack = [rootPath];
286
287 while (stack.length)
288 {
289 const dir = stack.pop();
290 if (!dir) continue;
291 const dirKey = path.resolve(dir);
292 if (visitedDirs.has(dirKey)) continue;
293 visitedDirs.add(dirKey);
294
295 let entries;
296 try
297 {
298 entries = fs.readdirSync(dir, { withFileTypes: true });
299 } catch
300 {
301 continue;
302 }
303
304 for (const entry of entries)
305 {
306 const fullPath = path.join(dir, entry.name);
307 if (entry.isDirectory())
308 {
309 stack.push(fullPath);
310 continue;
311 }
312 if (!entry.isFile()) continue;
313
314 const relativePath = path.relative(rootPath, fullPath);
315 const score = fuzzyMatchScore(query, entry.name)
316 ?? fuzzyMatchScore(query, relativePath);
317 if (score == null) continue;
318
319 let stat = null;
320 try { stat = fs.statSync(fullPath); } catch { /* ignore disappearing files */ }
321
322 results.push({
323 name: entry.name,
324 path: fullPath,
325 dir: path.dirname(fullPath),
326 rootPath,
327 relativePath,
328 size: stat ? stat.size : null,
329 mtime: stat ? stat.mtime.toISOString() : null,
330 score,
331 });
332
333 if (results.length > limit * 4)
334 {
335 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
336 results.length = limit * 2;
337 }
338 }
339 }
340 }
341
342 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
343 return results.slice(0, limit);
344 }
345
214 346 function rootAliasesFromConfig (config)
215 347 {
216 348 if (!config || typeof config !== 'object') return {};
@@ -759,6 +891,35 @@ router.get('/list', requireAuth, (req, res) =>
759 891 res.json({ items });
760 892 });
761 893
894 // ---------------------------------------------------------------------------
895 // GET /api/files/search?query=<text>&limit=<number>
896 // Fuzzy-searches all readable roots for files.
897 // ---------------------------------------------------------------------------
898 router.get('/search', requireAuth, (req, res) =>
899 {
900 const query = String(req.query.query || '').trim();
901 if (!query) return res.status(400).json({ error: 'query is required.' });
902
903 const { config, roots } = loadConfigAndRoots();
904 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
905 .filter((rootPath) =>
906 {
907 try
908 {
909 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
910 } catch
911 {
912 return false;
913 }
914 });
915
916 const results = searchFilesInRoots(query, readableRoots, req.query.limit);
917 res.json({
918 query,
919 results,
920 });
921 });
922
762 923 // ---------------------------------------------------------------------------
763 924 // GET /api/files/meta?file=<absolute-path>
764 925 // Returns file metadata from the DB. Lazily computes SHA-256 when missing.
@@ -1663,6 +1824,81 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1663 1824 res.json({ ok: true });
1664 1825 });
1665 1826
1827 // ---------------------------------------------------------------------------
1828 // GET /api/files/global-favicon-image
1829 // Serves the configured global favicon thumbnail file (cache-backed).
1830 // Public so <link rel="icon"> can fetch it without auth headers.
1831 // ---------------------------------------------------------------------------
1832 router.get('/global-favicon-image', async (req, res) =>
1833 {
1834 const config = loadConfig();
1835 const filePath = config && typeof config.globalFaviconPath === 'string'
1836 ? config.globalFaviconPath.trim()
1837 : '';
1838 if (!filePath) return res.status(404).end();
1839
1840 const thumb = await getCachedThumbnailInfo(filePath);
1841 if (!thumb || !thumb.thumbPath) return res.status(404).end();
1842 if (!fs.existsSync(thumb.thumbPath)) return res.status(404).end();
1843
1844 res.type(thumb.contentType || 'image/webp');
1845 res.sendFile(thumb.thumbPath);
1846 });
1847
1848 // ---------------------------------------------------------------------------
1849 // GET /api/files/global-favicon
1850 // Returns the configured global favicon source file path, if any.
1851 // ---------------------------------------------------------------------------
1852 router.get('/global-favicon', requireAuth, async (req, res) =>
1853 {
1854 const config = loadConfig();
1855 const filePath = config && typeof config.globalFaviconPath === 'string'
1856 ? config.globalFaviconPath.trim()
1857 : '';
1858 if (!filePath) return res.json({ favicon: null });
1859
1860 const thumb = await getCachedThumbnailInfo(filePath);
1861 if (!thumb) return res.json({ favicon: null });
1862
1863 res.json({ favicon: { filePath } });
1864 });
1865
1866 // ---------------------------------------------------------------------------
1867 // POST /api/files/global-favicon
1868 // Body: { imagePath } where imagePath may be null to clear.
1869 // Admin-only route for setting the global favicon source image.
1870 // ---------------------------------------------------------------------------
1871 router.post('/global-favicon', requireAuth, async (req, res) =>
1872 {
1873 if (!req.user || !req.user.isAdmin)
1874 {
1875 return res.status(403).json({ error: 'Admin access required.' });
1876 }
1877
1878 const rawImage = req.body && req.body.imagePath != null
1879 ? String(req.body.imagePath).trim()
1880 : null;
1881
1882 const config = loadConfig();
1883 const roots = getEffectivePaths(config.paths || []);
1884
1885 if (rawImage !== null)
1886 {
1887 const info = resolveRootForUser(rawImage, roots, req.user, config);
1888 if (!info || !canReadInfo(req.user, info))
1889 {
1890 return res.status(403).json({ error: 'Image not accessible.' });
1891 }
1892
1893 const thumb = await getCachedThumbnailInfo(rawImage);
1894 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
1895 }
1896
1897 config.globalFaviconPath = rawImage;
1898 saveConfig(config);
1899 res.json({ ok: true });
1900 });
1901
1666 1902 // ---------------------------------------------------------------------------
1667 1903 // POST /api/files/copy
1668 1904 // Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
@@ -211,6 +211,138 @@ function isAccessiblePath (absPath, roots, user, config)
211 return resolveRootForUser(absPath, roots, user, config) !== null;
211 return resolveRootForUser(absPath, roots, user, config) !== null;
212}
212}
213
213
214function readableSearchRootsForUser (user, config, roots)
215{
216 const out = [];
217 for (const root of roots)
218 {
219 const label = path.basename(root);
220 if (canRead(user, label)) out.push(root);
221 }
222
223 const personal = getUserFolderPath(config, user && user.username);
224 if (personal) out.push(personal);
225
226 // Deduplicate by resolved path.
227 const seen = new Set();
228 return out.filter((p) =>
229 {
230 const key = path.resolve(p);
231 if (seen.has(key)) return false;
232 seen.add(key);
233 return true;
234 });
235}
236
237function fuzzyMatchScore (needle, haystack)
238{
239 const q = String(needle || '').trim().toLowerCase();
240 const t = String(haystack || '').toLowerCase();
241 if (!q || !t) return null;
242
243 // Strong boost for contiguous substring matches.
244 const idx = t.indexOf(q);
245 if (idx >= 0)
246 {
247 const compactBonus = Math.max(0, 200 - idx);
248 const lengthBonus = Math.max(0, 120 - (t.length - q.length));
249 return 1200 + compactBonus + lengthBonus;
250 }
251
252 // Fallback: subsequence fuzzy match.
253 let qPos = 0;
254 let firstHit = -1;
255 let lastHit = -1;
256 let gaps = 0;
257
258 for (let i = 0; i < t.length && qPos < q.length; i++)
259 {
260 if (t[i] !== q[qPos]) continue;
261 if (firstHit === -1) firstHit = i;
262 if (lastHit >= 0) gaps += Math.max(0, i - lastHit - 1);
263 lastHit = i;
264 qPos += 1;
265 }
266
267 if (qPos !== q.length) return null;
268
269 const span = lastHit - firstHit + 1;
270 const compactness = Math.max(0, 300 - span);
271 const gapPenalty = Math.min(180, gaps * 3);
272 const startBonus = Math.max(0, 120 - firstHit);
273 return 700 + compactness + startBonus - gapPenalty;
274}
275
276function searchFilesInRoots (query, roots, maxResults)
277{
278 const limit = Math.max(1, Math.min(500, Number(maxResults) || 200));
279 const results = [];
280 const visitedDirs = new Set();
281
282 for (const root of roots)
283 {
284 const rootPath = path.resolve(root);
285 const stack = [rootPath];
286
287 while (stack.length)
288 {
289 const dir = stack.pop();
290 if (!dir) continue;
291 const dirKey = path.resolve(dir);
292 if (visitedDirs.has(dirKey)) continue;
293 visitedDirs.add(dirKey);
294
295 let entries;
296 try
297 {
298 entries = fs.readdirSync(dir, { withFileTypes: true });
299 } catch
300 {
301 continue;
302 }
303
304 for (const entry of entries)
305 {
306 const fullPath = path.join(dir, entry.name);
307 if (entry.isDirectory())
308 {
309 stack.push(fullPath);
310 continue;
311 }
312 if (!entry.isFile()) continue;
313
314 const relativePath = path.relative(rootPath, fullPath);
315 const score = fuzzyMatchScore(query, entry.name)
316 ?? fuzzyMatchScore(query, relativePath);
317 if (score == null) continue;
318
319 let stat = null;
320 try { stat = fs.statSync(fullPath); } catch { /* ignore disappearing files */ }
321
322 results.push({
323 name: entry.name,
324 path: fullPath,
325 dir: path.dirname(fullPath),
326 rootPath,
327 relativePath,
328 size: stat ? stat.size : null,
329 mtime: stat ? stat.mtime.toISOString() : null,
330 score,
331 });
332
333 if (results.length > limit * 4)
334 {
335 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
336 results.length = limit * 2;
337 }
338 }
339 }
340 }
341
342 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
343 return results.slice(0, limit);
344}
345
214function rootAliasesFromConfig (config)
346function rootAliasesFromConfig (config)
215{
347{
216 if (!config || typeof config !== 'object') return {};
348 if (!config || typeof config !== 'object') return {};
@@ -759,6 +891,35 @@ router.get('/list', requireAuth, (req, res) =>
759 res.json({ items });
891 res.json({ items });
760});
892});
761
893
894// ---------------------------------------------------------------------------
895// GET /api/files/search?query=<text>&limit=<number>
896// Fuzzy-searches all readable roots for files.
897// ---------------------------------------------------------------------------
898router.get('/search', requireAuth, (req, res) =>
899{
900 const query = String(req.query.query || '').trim();
901 if (!query) return res.status(400).json({ error: 'query is required.' });
902
903 const { config, roots } = loadConfigAndRoots();
904 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
905 .filter((rootPath) =>
906 {
907 try
908 {
909 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
910 } catch
911 {
912 return false;
913 }
914 });
915
916 const results = searchFilesInRoots(query, readableRoots, req.query.limit);
917 res.json({
918 query,
919 results,
920 });
921});
922
762// ---------------------------------------------------------------------------
923// ---------------------------------------------------------------------------
763// GET /api/files/meta?file=<absolute-path>
924// GET /api/files/meta?file=<absolute-path>
764// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
925// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
@@ -1663,6 +1824,81 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1663 res.json({ ok: true });
1824 res.json({ ok: true });
1664});
1825});
1665
1826
1827// ---------------------------------------------------------------------------
1828// GET /api/files/global-favicon-image
1829// Serves the configured global favicon thumbnail file (cache-backed).
1830// Public so <link rel="icon"> can fetch it without auth headers.
1831// ---------------------------------------------------------------------------
1832router.get('/global-favicon-image', async (req, res) =>
1833{
1834 const config = loadConfig();
1835 const filePath = config && typeof config.globalFaviconPath === 'string'
1836 ? config.globalFaviconPath.trim()
1837 : '';
1838 if (!filePath) return res.status(404).end();
1839
1840 const thumb = await getCachedThumbnailInfo(filePath);
1841 if (!thumb || !thumb.thumbPath) return res.status(404).end();
1842 if (!fs.existsSync(thumb.thumbPath)) return res.status(404).end();
1843
1844 res.type(thumb.contentType || 'image/webp');
1845 res.sendFile(thumb.thumbPath);
1846});
1847
1848// ---------------------------------------------------------------------------
1849// GET /api/files/global-favicon
1850// Returns the configured global favicon source file path, if any.
1851// ---------------------------------------------------------------------------
1852router.get('/global-favicon', requireAuth, async (req, res) =>
1853{
1854 const config = loadConfig();
1855 const filePath = config && typeof config.globalFaviconPath === 'string'
1856 ? config.globalFaviconPath.trim()
1857 : '';
1858 if (!filePath) return res.json({ favicon: null });
1859
1860 const thumb = await getCachedThumbnailInfo(filePath);
1861 if (!thumb) return res.json({ favicon: null });
1862
1863 res.json({ favicon: { filePath } });
1864});
1865
1866// ---------------------------------------------------------------------------
1867// POST /api/files/global-favicon
1868// Body: { imagePath } where imagePath may be null to clear.
1869// Admin-only route for setting the global favicon source image.
1870// ---------------------------------------------------------------------------
1871router.post('/global-favicon', requireAuth, async (req, res) =>
1872{
1873 if (!req.user || !req.user.isAdmin)
1874 {
1875 return res.status(403).json({ error: 'Admin access required.' });
1876 }
1877
1878 const rawImage = req.body && req.body.imagePath != null
1879 ? String(req.body.imagePath).trim()
1880 : null;
1881
1882 const config = loadConfig();
1883 const roots = getEffectivePaths(config.paths || []);
1884
1885 if (rawImage !== null)
1886 {
1887 const info = resolveRootForUser(rawImage, roots, req.user, config);
1888 if (!info || !canReadInfo(req.user, info))
1889 {
1890 return res.status(403).json({ error: 'Image not accessible.' });
1891 }
1892
1893 const thumb = await getCachedThumbnailInfo(rawImage);
1894 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
1895 }
1896
1897 config.globalFaviconPath = rawImage;
1898 saveConfig(config);
1899 res.json({ ok: true });
1900});
1901
1666// ---------------------------------------------------------------------------
1902// ---------------------------------------------------------------------------
1667// POST /api/files/copy
1903// POST /api/files/copy
1668// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1904// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
tests/files.routes.test.js +83 −1
@@ -10,6 +10,7 @@ const { once } = require('events');
10 10 let mockPaths = [];
11 11 let mockUserPath = null;
12 12 let mockRootAliases = {};
13 let mockGlobalFaviconPath = null;
13 14 let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
14 15 let mockThumbPath = null;
15 16 let mockFolderImages = [];
@@ -54,11 +55,18 @@ jest.mock('../server/db', () =>
54 55 });
55 56
56 57 jest.mock('../server/config', () => ({
57 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: { ...mockRootAliases } }),
58 loadConfig: () => ({
59 port: 3000,
60 paths: [...mockPaths],
61 userPath: mockUserPath,
62 rootAliases: { ...mockRootAliases },
63 globalFaviconPath: mockGlobalFaviconPath,
64 }),
58 65 saveConfig: (config) =>
59 66 {
60 67 mockPaths = [...(config.paths || [])];
61 68 mockRootAliases = { ...(config.rootAliases || {}) };
69 mockGlobalFaviconPath = config.globalFaviconPath || null;
62 70 },
63 71 getEffectivePaths: (paths) => paths,
64 72 getAllowedRoot: (targetPath, roots) =>
@@ -163,6 +171,7 @@ beforeEach(() =>
163 171 fs.mkdirSync(mockUserPath, { recursive: true });
164 172 }
165 173 mockRootAliases = {};
174 mockGlobalFaviconPath = null;
166 175 mockUserPath = null;
167 176 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
168 177 mockThumbPath = null;
@@ -724,6 +733,79 @@ describe('folder icon endpoints', () =>
724 733 });
725 734 });
726 735
736 describe('file search endpoint', () =>
737 {
738 test('GET /api/files/search returns fuzzy-matched files across folders', async () =>
739 {
740 const movieDir = path.join(rootDir, 'Movies');
741 const docsDir = path.join(rootDir, 'Docs');
742 fs.mkdirSync(movieDir, { recursive: true });
743 fs.mkdirSync(docsDir, { recursive: true });
744 fs.writeFileSync(path.join(movieDir, 'Dragon Ball Super.mkv'), 'vid');
745 fs.writeFileSync(path.join(docsDir, 'notes.txt'), 'txt');
746
747 const { status, body } = await req('GET', '/api/files/search?query=dbs');
748 expect(status).toBe(200);
749 expect(body.query).toBe('dbs');
750 expect(body.results.length).toBeGreaterThan(0);
751 expect(body.results[0].name).toBe('Dragon Ball Super.mkv');
752 });
753
754 test('GET /api/files/search returns 400 when query is missing', async () =>
755 {
756 const { status } = await req('GET', '/api/files/search');
757 expect(status).toBe(400);
758 });
759 });
760
761 describe('global favicon endpoints', () =>
762 {
763 test('GET /api/files/global-favicon returns null when unset', async () =>
764 {
765 const { status, body } = await req('GET', '/api/files/global-favicon');
766 expect(status).toBe(200);
767 expect(body.favicon).toBeNull();
768 });
769
770 test('POST /api/files/global-favicon stores selected image path', async () =>
771 {
772 const imgPath = path.join(rootDir, 'cover.jpg');
773 const thumbPath = path.join(rootDir, 'cover.webp');
774 fs.writeFileSync(imgPath, 'img');
775 fs.writeFileSync(thumbPath, 'thumb');
776 mockThumbPath = thumbPath;
777
778 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
779 expect(status).toBe(200);
780 expect(body.ok).toBe(true);
781 expect(mockGlobalFaviconPath).toBe(imgPath);
782
783 const fetched = await req('GET', '/api/files/global-favicon');
784 expect(fetched.status).toBe(200);
785 expect(fetched.body.favicon).toEqual({ filePath: imgPath });
786 });
787
788 test('POST /api/files/global-favicon clears the configured favicon', async () =>
789 {
790 mockGlobalFaviconPath = path.join(rootDir, 'old.jpg');
791
792 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: null });
793 expect(status).toBe(200);
794 expect(body.ok).toBe(true);
795 expect(mockGlobalFaviconPath).toBeNull();
796 });
797
798 test('POST /api/files/global-favicon is admin-only', async () =>
799 {
800 mockUser = { username: 'reader', isAdmin: false, permissions: {} };
801 const imgPath = path.join(rootDir, 'cover.jpg');
802 fs.writeFileSync(imgPath, 'img');
803
804 const { status } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
805 expect(status).toBe(403);
806 });
807 });
808
727 809 // ---------------------------------------------------------------------------
728 810 // GET /api/files/download-zip
729 811 // ---------------------------------------------------------------------------
@@ -10,6 +10,7 @@ const { once } = require('events');
10let mockPaths = [];
10let mockPaths = [];
11let mockUserPath = null;
11let mockUserPath = null;
12let mockRootAliases = {};
12let mockRootAliases = {};
13let mockGlobalFaviconPath = null;
13let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
14let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
14let mockThumbPath = null;
15let mockThumbPath = null;
15let mockFolderImages = [];
16let mockFolderImages = [];
@@ -54,11 +55,18 @@ jest.mock('../server/db', () =>
54});
55});
55
56
56jest.mock('../server/config', () => ({
57jest.mock('../server/config', () => ({
57 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: { ...mockRootAliases } }),
58 loadConfig: () => ({
59 port: 3000,
60 paths: [...mockPaths],
61 userPath: mockUserPath,
62 rootAliases: { ...mockRootAliases },
63 globalFaviconPath: mockGlobalFaviconPath,
64 }),
58 saveConfig: (config) =>
65 saveConfig: (config) =>
59 {
66 {
60 mockPaths = [...(config.paths || [])];
67 mockPaths = [...(config.paths || [])];
61 mockRootAliases = { ...(config.rootAliases || {}) };
68 mockRootAliases = { ...(config.rootAliases || {}) };
69 mockGlobalFaviconPath = config.globalFaviconPath || null;
62 },
70 },
63 getEffectivePaths: (paths) => paths,
71 getEffectivePaths: (paths) => paths,
64 getAllowedRoot: (targetPath, roots) =>
72 getAllowedRoot: (targetPath, roots) =>
@@ -163,6 +171,7 @@ beforeEach(() =>
163 fs.mkdirSync(mockUserPath, { recursive: true });
171 fs.mkdirSync(mockUserPath, { recursive: true });
164 }
172 }
165 mockRootAliases = {};
173 mockRootAliases = {};
174 mockGlobalFaviconPath = null;
166 mockUserPath = null;
175 mockUserPath = null;
167 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
176 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
168 mockThumbPath = null;
177 mockThumbPath = null;
@@ -724,6 +733,79 @@ describe('folder icon endpoints', () =>
724 });
733 });
725});
734});
726
735
736describe('file search endpoint', () =>
737{
738 test('GET /api/files/search returns fuzzy-matched files across folders', async () =>
739 {
740 const movieDir = path.join(rootDir, 'Movies');
741 const docsDir = path.join(rootDir, 'Docs');
742 fs.mkdirSync(movieDir, { recursive: true });
743 fs.mkdirSync(docsDir, { recursive: true });
744 fs.writeFileSync(path.join(movieDir, 'Dragon Ball Super.mkv'), 'vid');
745 fs.writeFileSync(path.join(docsDir, 'notes.txt'), 'txt');
746
747 const { status, body } = await req('GET', '/api/files/search?query=dbs');
748 expect(status).toBe(200);
749 expect(body.query).toBe('dbs');
750 expect(body.results.length).toBeGreaterThan(0);
751 expect(body.results[0].name).toBe('Dragon Ball Super.mkv');
752 });
753
754 test('GET /api/files/search returns 400 when query is missing', async () =>
755 {
756 const { status } = await req('GET', '/api/files/search');
757 expect(status).toBe(400);
758 });
759});
760
761describe('global favicon endpoints', () =>
762{
763 test('GET /api/files/global-favicon returns null when unset', async () =>
764 {
765 const { status, body } = await req('GET', '/api/files/global-favicon');
766 expect(status).toBe(200);
767 expect(body.favicon).toBeNull();
768 });
769
770 test('POST /api/files/global-favicon stores selected image path', async () =>
771 {
772 const imgPath = path.join(rootDir, 'cover.jpg');
773 const thumbPath = path.join(rootDir, 'cover.webp');
774 fs.writeFileSync(imgPath, 'img');
775 fs.writeFileSync(thumbPath, 'thumb');
776 mockThumbPath = thumbPath;
777
778 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
779 expect(status).toBe(200);
780 expect(body.ok).toBe(true);
781 expect(mockGlobalFaviconPath).toBe(imgPath);
782
783 const fetched = await req('GET', '/api/files/global-favicon');
784 expect(fetched.status).toBe(200);
785 expect(fetched.body.favicon).toEqual({ filePath: imgPath });
786 });
787
788 test('POST /api/files/global-favicon clears the configured favicon', async () =>
789 {
790 mockGlobalFaviconPath = path.join(rootDir, 'old.jpg');
791
792 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: null });
793 expect(status).toBe(200);
794 expect(body.ok).toBe(true);
795 expect(mockGlobalFaviconPath).toBeNull();
796 });
797
798 test('POST /api/files/global-favicon is admin-only', async () =>
799 {
800 mockUser = { username: 'reader', isAdmin: false, permissions: {} };
801 const imgPath = path.join(rootDir, 'cover.jpg');
802 fs.writeFileSync(imgPath, 'img');
803
804 const { status } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
805 expect(status).toBe(403);
806 });
807});
808
727// ---------------------------------------------------------------------------
809// ---------------------------------------------------------------------------
728// GET /api/files/download-zip
810// GET /api/files/download-zip
729// ---------------------------------------------------------------------------
811// ---------------------------------------------------------------------------