BlueGit

timfa filemanager

Add scalable global favicon image search across accessible roots

timfa Tim Falken · pushed by timfa

Authored 2026-05-17 · 6 months ago

Hash
6b2c38e525c59eead8ae9ba5bab4acb1a12fc7ed
Parent
4756368a
5 files changed +360 −17
.github/technical-reference.md +2 −0
@@ -73,6 +73,7 @@
73 73 - GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
74 74 - POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
75 75 - GET /api/files/search - Fuzzy-searches all readable roots (and personal folder when configured) for files, returning ranked matches with path metadata.
76 - GET /api/files/search-images - Fuzzy-searches readable roots for image files with ready thumbnails, returning capped results plus scan-truncation metadata for scalable global favicon selection.
76 77 - GET /api/files/global-favicon-image - Publicly serves the configured global favicon thumbnail file so browsers can load `<link rel="icon">` without auth headers.
77 78 - GET /api/files/global-favicon - Returns the configured global favicon source file path ({favicon:{filePath}} or {favicon:null}).
78 79 - POST /api/files/global-favicon - Admin-only route that sets or clears the global favicon source image; image must have a cached thumbnail.
@@ -172,6 +173,7 @@
172 173 - openFolderIconPicker(item) - Opens the folder icon picker modal; shows cached-thumbnail files from the folder (including video thumbnails); allows selection, clearing, and cancellation.
173 174 - openIconPickerModal(options) - Shared icon-picker modal used by folder-icon and global-favicon flows; includes live thumbnail-name filtering.
174 175 - openGlobalFaviconPicker() - Opens the shared icon picker for the current folder and sets/clears global favicon via `/files/global-favicon`.
176 - openGlobalFaviconPicker() - Opens a debounced, server-backed image-search modal across all accessible roots and sets/clears global favicon via `/files/global-favicon`.
175 177 - refreshGlobalFavicon() - Reads `/files/global-favicon`, updates topbar preview button, and applies/removes the page `<link rel="icon">` URL.
176 178 - refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
177 179 - disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
@@ -73,6 +73,7 @@
73- GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
73- GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
74- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
74- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
75- GET /api/files/search - Fuzzy-searches all readable roots (and personal folder when configured) for files, returning ranked matches with path metadata.
75- GET /api/files/search - Fuzzy-searches all readable roots (and personal folder when configured) for files, returning ranked matches with path metadata.
76- GET /api/files/search-images - Fuzzy-searches readable roots for image files with ready thumbnails, returning capped results plus scan-truncation metadata for scalable global favicon selection.
76- GET /api/files/global-favicon-image - Publicly serves the configured global favicon thumbnail file so browsers can load `<link rel="icon">` without auth headers.
77- GET /api/files/global-favicon-image - Publicly serves the configured global favicon thumbnail file so browsers can load `<link rel="icon">` without auth headers.
77- GET /api/files/global-favicon - Returns the configured global favicon source file path ({favicon:{filePath}} or {favicon:null}).
78- GET /api/files/global-favicon - Returns the configured global favicon source file path ({favicon:{filePath}} or {favicon:null}).
78- POST /api/files/global-favicon - Admin-only route that sets or clears the global favicon source image; image must have a cached thumbnail.
79- POST /api/files/global-favicon - Admin-only route that sets or clears the global favicon source image; image must have a cached thumbnail.
@@ -172,6 +173,7 @@
172- openFolderIconPicker(item) - Opens the folder icon picker modal; shows cached-thumbnail files from the folder (including video thumbnails); allows selection, clearing, and cancellation.
173- openFolderIconPicker(item) - Opens the folder icon picker modal; shows cached-thumbnail files from the folder (including video thumbnails); allows selection, clearing, and cancellation.
173- openIconPickerModal(options) - Shared icon-picker modal used by folder-icon and global-favicon flows; includes live thumbnail-name filtering.
174- openIconPickerModal(options) - Shared icon-picker modal used by folder-icon and global-favicon flows; includes live thumbnail-name filtering.
174- openGlobalFaviconPicker() - Opens the shared icon picker for the current folder and sets/clears global favicon via `/files/global-favicon`.
175- openGlobalFaviconPicker() - Opens the shared icon picker for the current folder and sets/clears global favicon via `/files/global-favicon`.
176- openGlobalFaviconPicker() - Opens a debounced, server-backed image-search modal across all accessible roots and sets/clears global favicon via `/files/global-favicon`.
175- refreshGlobalFavicon() - Reads `/files/global-favicon`, updates topbar preview button, and applies/removes the page `<link rel="icon">` URL.
177- refreshGlobalFavicon() - Reads `/files/global-favicon`, updates topbar preview button, and applies/removes the page `<link rel="icon">` URL.
176- refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
178- refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
177- disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
179- disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
.github/tests.md +1 −0
@@ -45,6 +45,7 @@
45 45 - `GET /api/files/root-access`
46 46 - `folder icon endpoints`
47 47 - `file search endpoint`
48 - `image search endpoint`
48 49 - `global favicon endpoints`
49 50 - `GET /api/files/download-zip`
50 51 - `video streaming routes`
@@ -45,6 +45,7 @@
45- `GET /api/files/root-access`
45- `GET /api/files/root-access`
46- `folder icon endpoints`
46- `folder icon endpoints`
47- `file search endpoint`
47- `file search endpoint`
48- `image search endpoint`
48- `global favicon endpoints`
49- `global favicon endpoints`
49- `GET /api/files/download-zip`
50- `GET /api/files/download-zip`
50- `video streaming routes`
51- `video streaming routes`
public/app.js +193 −17
@@ -3214,30 +3214,206 @@ async function openGlobalFaviconPicker ()
3214 3214 return;
3215 3215 }
3216 3216
3217 const rootFallback = STATE.currentRoot
3218 ? STATE.currentRoot.path
3219 : (STATE.roots[0] ? STATE.roots[0].path : null);
3220 const dirPath = STATE.currentDir || rootFallback;
3221 await openIconPickerModal({
3222 dirPath,
3223 titleText: 'Set global favicon',
3224 subtitleText: 'Select a file thumbnail to use as the global favicon.',
3225 emptyText: 'No files with cached thumbnails were found inside this folder.',
3226 confirmLabel: 'Set favicon',
3227 clearLabel: 'Clear favicon',
3228 onSelect: async (imagePath) =>
3217 const existingIconOverlay = document.getElementById('folder-icon-picker');
3218 if (existingIconOverlay) existingIconOverlay.remove();
3219
3220 const overlay = document.createElement('div');
3221 overlay.id = 'folder-icon-picker';
3222 overlay.className = 'modal-overlay';
3223
3224 const modal = document.createElement('div');
3225 modal.className = 'modal folder-icon-modal';
3226
3227 const closeBtn = document.createElement('button');
3228 closeBtn.className = 'modal-close';
3229 closeBtn.setAttribute('aria-label', 'Close');
3230 closeBtn.textContent = '✕';
3231
3232 const title = document.createElement('h2');
3233 title.textContent = 'Set global favicon';
3234
3235 const filterInput = document.createElement('input');
3236 filterInput.type = 'text';
3237 filterInput.className = 'folder-icon-filter';
3238 filterInput.placeholder = 'Search images across all folders';
3239 filterInput.setAttribute('aria-label', 'Search images');
3240
3241 const subtitle = document.createElement('p');
3242 subtitle.className = 'muted';
3243 subtitle.textContent = 'Type at least 2 characters to search accessible images.';
3244
3245 const grid = document.createElement('div');
3246 grid.className = 'folder-icon-grid';
3247
3248 const dialogActions = document.createElement('div');
3249 dialogActions.className = 'dialog-actions';
3250
3251 const clearBtn = document.createElement('button');
3252 clearBtn.textContent = 'Clear favicon';
3253 clearBtn.addEventListener('click', async () =>
3254 {
3255 try
3229 3256 {
3230 await api('POST', '/files/global-favicon', { imagePath });
3257 await api('POST', '/files/global-favicon', { imagePath: null });
3231 3258 STATE.faviconVersion = Date.now();
3232 3259 await refreshGlobalFavicon();
3233 },
3234 onClear: async () =>
3260 }
3261 catch (err)
3235 3262 {
3236 await api('POST', '/files/global-favicon', { imagePath: null });
3263 toast('Failed to clear icon: ' + err.message, 'err');
3264 return;
3265 }
3266 hide();
3267 });
3268
3269 const cancelBtn = document.createElement('button');
3270 cancelBtn.textContent = 'Cancel';
3271 cancelBtn.addEventListener('click', () => hide());
3272
3273 const confirmBtn = document.createElement('button');
3274 confirmBtn.className = 'primary';
3275 confirmBtn.textContent = 'Set favicon';
3276 confirmBtn.disabled = true;
3277
3278 let selectedPath = null;
3279 let searchToken = 0;
3280 let searchTimer = null;
3281
3282 confirmBtn.addEventListener('click', async () =>
3283 {
3284 if (!selectedPath) return;
3285 try
3286 {
3287 await api('POST', '/files/global-favicon', { imagePath: selectedPath });
3237 3288 STATE.faviconVersion = Date.now();
3238 3289 await refreshGlobalFavicon();
3239 },
3290 }
3291 catch (err)
3292 {
3293 toast('Failed to set icon: ' + err.message, 'err');
3294 return;
3295 }
3296 hide();
3297 });
3298
3299 function revokeCellThumbs ()
3300 {
3301 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) =>
3302 {
3303 URL.revokeObjectURL(img.src);
3304 });
3305 }
3306
3307 function renderResults (items)
3308 {
3309 selectedPath = null;
3310 confirmBtn.disabled = true;
3311 revokeCellThumbs();
3312 grid.innerHTML = '';
3313
3314 for (const { path: filePath, name } of (items || []))
3315 {
3316 const cell = document.createElement('div');
3317 cell.className = 'folder-icon-cell';
3318 cell.dataset.path = filePath;
3319
3320 const imgEl = document.createElement('img');
3321 imgEl.alt = name;
3322 imgEl.className = 'folder-icon-thumb';
3323
3324 const label = document.createElement('div');
3325 label.className = 'folder-icon-label';
3326 label.textContent = name;
3327
3328 cell.appendChild(imgEl);
3329 cell.appendChild(label);
3330
3331 cell.addEventListener('click', () =>
3332 {
3333 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
3334 cell.classList.add('selected');
3335 selectedPath = filePath;
3336 confirmBtn.disabled = false;
3337 });
3338
3339 grid.appendChild(cell);
3340
3341 void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, {
3342 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
3343 }).then(async (r) =>
3344 {
3345 if (!r.ok || !overlay.isConnected) return;
3346 const blob = await r.blob();
3347 const url = URL.createObjectURL(blob);
3348 imgEl.src = url;
3349 }).catch(() => { });
3350 }
3351 }
3352
3353 async function runSearchNow ()
3354 {
3355 const query = String(filterInput.value || '').trim();
3356 searchToken += 1;
3357 const token = searchToken;
3358
3359 if (query.length < 2)
3360 {
3361 subtitle.textContent = 'Type at least 2 characters to search accessible images.';
3362 renderResults([]);
3363 return;
3364 }
3365
3366 subtitle.textContent = 'Searching…';
3367 const data = await api('GET', `/files/search-images?query=${encodeURIComponent(query)}&limit=80`).catch(() => null);
3368 if (!overlay.isConnected || token !== searchToken) return;
3369
3370 const results = Array.isArray(data && data.results) ? data.results : [];
3371 renderResults(results);
3372
3373 if (!results.length)
3374 {
3375 subtitle.textContent = 'No matching thumbnails were found.';
3376 return;
3377 }
3378
3379 const suffix = data && data.truncated
3380 ? ` Scanned first ${Number(data.scannedFiles) || 0} files; refine your search for more.`
3381 : '';
3382 subtitle.textContent = `${results.length} matching image${results.length === 1 ? '' : 's'} found.${suffix}`;
3383 }
3384
3385 filterInput.addEventListener('input', () =>
3386 {
3387 if (searchTimer) clearTimeout(searchTimer);
3388 searchTimer = setTimeout(() =>
3389 {
3390 void runSearchNow();
3391 }, 240);
3240 3392 });
3393
3394 dialogActions.appendChild(clearBtn);
3395 dialogActions.appendChild(cancelBtn);
3396 dialogActions.appendChild(confirmBtn);
3397
3398 modal.appendChild(closeBtn);
3399 modal.appendChild(title);
3400 modal.appendChild(filterInput);
3401 modal.appendChild(subtitle);
3402 modal.appendChild(grid);
3403 modal.appendChild(dialogActions);
3404 overlay.appendChild(modal);
3405 document.body.appendChild(overlay);
3406
3407 function hide ()
3408 {
3409 if (searchTimer) clearTimeout(searchTimer);
3410 overlay.remove();
3411 revokeCellThumbs();
3412 }
3413
3414 closeBtn.addEventListener('click', hide);
3415 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
3416 filterInput.focus();
3241 3417 }
3242 3418
3243 3419 function refreshAfterIconChange (item)
@@ -3214,30 +3214,206 @@ async function openGlobalFaviconPicker ()
3214 return;
3214 return;
3215 }
3215 }
3216
3216
3217 const rootFallback = STATE.currentRoot
3217 const existingIconOverlay = document.getElementById('folder-icon-picker');
3218 ? STATE.currentRoot.path
3218 if (existingIconOverlay) existingIconOverlay.remove();
3219 : (STATE.roots[0] ? STATE.roots[0].path : null);
3219
3220 const dirPath = STATE.currentDir || rootFallback;
3220 const overlay = document.createElement('div');
3221 await openIconPickerModal({
3221 overlay.id = 'folder-icon-picker';
3222 dirPath,
3222 overlay.className = 'modal-overlay';
3223 titleText: 'Set global favicon',
3223
3224 subtitleText: 'Select a file thumbnail to use as the global favicon.',
3224 const modal = document.createElement('div');
3225 emptyText: 'No files with cached thumbnails were found inside this folder.',
3225 modal.className = 'modal folder-icon-modal';
3226 confirmLabel: 'Set favicon',
3226
3227 clearLabel: 'Clear favicon',
3227 const closeBtn = document.createElement('button');
3228 onSelect: async (imagePath) =>
3228 closeBtn.className = 'modal-close';
3229 closeBtn.setAttribute('aria-label', 'Close');
3230 closeBtn.textContent = '✕';
3231
3232 const title = document.createElement('h2');
3233 title.textContent = 'Set global favicon';
3234
3235 const filterInput = document.createElement('input');
3236 filterInput.type = 'text';
3237 filterInput.className = 'folder-icon-filter';
3238 filterInput.placeholder = 'Search images across all folders';
3239 filterInput.setAttribute('aria-label', 'Search images');
3240
3241 const subtitle = document.createElement('p');
3242 subtitle.className = 'muted';
3243 subtitle.textContent = 'Type at least 2 characters to search accessible images.';
3244
3245 const grid = document.createElement('div');
3246 grid.className = 'folder-icon-grid';
3247
3248 const dialogActions = document.createElement('div');
3249 dialogActions.className = 'dialog-actions';
3250
3251 const clearBtn = document.createElement('button');
3252 clearBtn.textContent = 'Clear favicon';
3253 clearBtn.addEventListener('click', async () =>
3254 {
3255 try
3229 {
3256 {
3230 await api('POST', '/files/global-favicon', { imagePath });
3257 await api('POST', '/files/global-favicon', { imagePath: null });
3231 STATE.faviconVersion = Date.now();
3258 STATE.faviconVersion = Date.now();
3232 await refreshGlobalFavicon();
3259 await refreshGlobalFavicon();
3233 },
3260 }
3234 onClear: async () =>
3261 catch (err)
3235 {
3262 {
3236 await api('POST', '/files/global-favicon', { imagePath: null });
3263 toast('Failed to clear icon: ' + err.message, 'err');
3264 return;
3265 }
3266 hide();
3267 });
3268
3269 const cancelBtn = document.createElement('button');
3270 cancelBtn.textContent = 'Cancel';
3271 cancelBtn.addEventListener('click', () => hide());
3272
3273 const confirmBtn = document.createElement('button');
3274 confirmBtn.className = 'primary';
3275 confirmBtn.textContent = 'Set favicon';
3276 confirmBtn.disabled = true;
3277
3278 let selectedPath = null;
3279 let searchToken = 0;
3280 let searchTimer = null;
3281
3282 confirmBtn.addEventListener('click', async () =>
3283 {
3284 if (!selectedPath) return;
3285 try
3286 {
3287 await api('POST', '/files/global-favicon', { imagePath: selectedPath });
3237 STATE.faviconVersion = Date.now();
3288 STATE.faviconVersion = Date.now();
3238 await refreshGlobalFavicon();
3289 await refreshGlobalFavicon();
3239 },
3290 }
3291 catch (err)
3292 {
3293 toast('Failed to set icon: ' + err.message, 'err');
3294 return;
3295 }
3296 hide();
3297 });
3298
3299 function revokeCellThumbs ()
3300 {
3301 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) =>
3302 {
3303 URL.revokeObjectURL(img.src);
3304 });
3305 }
3306
3307 function renderResults (items)
3308 {
3309 selectedPath = null;
3310 confirmBtn.disabled = true;
3311 revokeCellThumbs();
3312 grid.innerHTML = '';
3313
3314 for (const { path: filePath, name } of (items || []))
3315 {
3316 const cell = document.createElement('div');
3317 cell.className = 'folder-icon-cell';
3318 cell.dataset.path = filePath;
3319
3320 const imgEl = document.createElement('img');
3321 imgEl.alt = name;
3322 imgEl.className = 'folder-icon-thumb';
3323
3324 const label = document.createElement('div');
3325 label.className = 'folder-icon-label';
3326 label.textContent = name;
3327
3328 cell.appendChild(imgEl);
3329 cell.appendChild(label);
3330
3331 cell.addEventListener('click', () =>
3332 {
3333 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
3334 cell.classList.add('selected');
3335 selectedPath = filePath;
3336 confirmBtn.disabled = false;
3337 });
3338
3339 grid.appendChild(cell);
3340
3341 void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, {
3342 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
3343 }).then(async (r) =>
3344 {
3345 if (!r.ok || !overlay.isConnected) return;
3346 const blob = await r.blob();
3347 const url = URL.createObjectURL(blob);
3348 imgEl.src = url;
3349 }).catch(() => { });
3350 }
3351 }
3352
3353 async function runSearchNow ()
3354 {
3355 const query = String(filterInput.value || '').trim();
3356 searchToken += 1;
3357 const token = searchToken;
3358
3359 if (query.length < 2)
3360 {
3361 subtitle.textContent = 'Type at least 2 characters to search accessible images.';
3362 renderResults([]);
3363 return;
3364 }
3365
3366 subtitle.textContent = 'Searching…';
3367 const data = await api('GET', `/files/search-images?query=${encodeURIComponent(query)}&limit=80`).catch(() => null);
3368 if (!overlay.isConnected || token !== searchToken) return;
3369
3370 const results = Array.isArray(data && data.results) ? data.results : [];
3371 renderResults(results);
3372
3373 if (!results.length)
3374 {
3375 subtitle.textContent = 'No matching thumbnails were found.';
3376 return;
3377 }
3378
3379 const suffix = data && data.truncated
3380 ? ` Scanned first ${Number(data.scannedFiles) || 0} files; refine your search for more.`
3381 : '';
3382 subtitle.textContent = `${results.length} matching image${results.length === 1 ? '' : 's'} found.${suffix}`;
3383 }
3384
3385 filterInput.addEventListener('input', () =>
3386 {
3387 if (searchTimer) clearTimeout(searchTimer);
3388 searchTimer = setTimeout(() =>
3389 {
3390 void runSearchNow();
3391 }, 240);
3240 });
3392 });
3393
3394 dialogActions.appendChild(clearBtn);
3395 dialogActions.appendChild(cancelBtn);
3396 dialogActions.appendChild(confirmBtn);
3397
3398 modal.appendChild(closeBtn);
3399 modal.appendChild(title);
3400 modal.appendChild(filterInput);
3401 modal.appendChild(subtitle);
3402 modal.appendChild(grid);
3403 modal.appendChild(dialogActions);
3404 overlay.appendChild(modal);
3405 document.body.appendChild(overlay);
3406
3407 function hide ()
3408 {
3409 if (searchTimer) clearTimeout(searchTimer);
3410 overlay.remove();
3411 revokeCellThumbs();
3412 }
3413
3414 closeBtn.addEventListener('click', hide);
3415 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
3416 filterInput.focus();
3241}
3417}
3242
3418
3243function refreshAfterIconChange (item)
3419function refreshAfterIconChange (item)
server/routes/files.js +138 −0
@@ -273,6 +273,16 @@ function fuzzyMatchScore (needle, haystack)
273 273 return 700 + compactness + startBonus - gapPenalty;
274 274 }
275 275
276 const SEARCHABLE_IMAGE_EXTS = new Set([
277 '.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.svg', '.avif', '.ico', '.tif', '.tiff',
278 ]);
279
280 function isSearchableImageFileName (name)
281 {
282 const ext = path.extname(String(name || '')).toLowerCase();
283 return SEARCHABLE_IMAGE_EXTS.has(ext);
284 }
285
276 286 function searchFilesInRoots (query, roots, maxResults)
277 287 {
278 288 const limit = Math.max(1, Math.min(500, Number(maxResults) || 200));
@@ -343,6 +353,97 @@ function searchFilesInRoots (query, roots, maxResults)
343 353 return results.slice(0, limit);
344 354 }
345 355
356 async function searchImagesWithThumbnailsInRoots (query, roots, maxResults)
357 {
358 const limit = Math.max(1, Math.min(120, Number(maxResults) || 60));
359 const maxScannedFiles = 25000;
360 const results = [];
361 const visitedDirs = new Set();
362 let scannedFiles = 0;
363 let truncated = false;
364
365 for (const root of roots)
366 {
367 if (results.length >= limit || scannedFiles >= maxScannedFiles) break;
368
369 const rootPath = path.resolve(root);
370 const stack = [rootPath];
371
372 while (stack.length)
373 {
374 if (results.length >= limit || scannedFiles >= maxScannedFiles) break;
375
376 const dir = stack.pop();
377 if (!dir) continue;
378 const dirKey = path.resolve(dir);
379 if (visitedDirs.has(dirKey)) continue;
380 visitedDirs.add(dirKey);
381
382 let entries;
383 try
384 {
385 entries = fs.readdirSync(dir, { withFileTypes: true });
386 } catch
387 {
388 continue;
389 }
390
391 for (const entry of entries)
392 {
393 if (results.length >= limit || scannedFiles >= maxScannedFiles) break;
394
395 const fullPath = path.join(dir, entry.name);
396 if (entry.isDirectory())
397 {
398 stack.push(fullPath);
399 continue;
400 }
401 if (!entry.isFile()) continue;
402
403 scannedFiles += 1;
404 if (!isSearchableImageFileName(entry.name)) continue;
405
406 const relativePath = path.relative(rootPath, fullPath);
407 const score = fuzzyMatchScore(query, entry.name)
408 ?? fuzzyMatchScore(query, relativePath);
409 if (score == null) continue;
410
411 // Only include files that already have a ready thumbnail.
412 const thumb = await getCachedThumbnailInfo(fullPath);
413 if (!thumb) continue;
414
415 let stat = null;
416 try { stat = fs.statSync(fullPath); } catch { /* ignore disappearing files */ }
417
418 results.push({
419 name: entry.name,
420 path: fullPath,
421 dir: path.dirname(fullPath),
422 rootPath,
423 relativePath,
424 size: stat ? stat.size : null,
425 mtime: stat ? stat.mtime.toISOString() : null,
426 score,
427 });
428
429 if (results.length > limit * 3)
430 {
431 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
432 results.length = limit;
433 }
434 }
435 }
436 }
437
438 if (scannedFiles >= maxScannedFiles) truncated = true;
439 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
440 return {
441 results: results.slice(0, limit),
442 scannedFiles,
443 truncated,
444 };
445 }
446
346 447 function rootAliasesFromConfig (config)
347 448 {
348 449 if (!config || typeof config !== 'object') return {};
@@ -920,6 +1021,43 @@ router.get('/search', requireAuth, (req, res) =>
920 1021 });
921 1022 });
922 1023
1024 // ---------------------------------------------------------------------------
1025 // GET /api/files/search-images?query=<text>&limit=<number>
1026 // Fuzzy-searches readable roots for image files that have ready thumbnails.
1027 // ---------------------------------------------------------------------------
1028 router.get('/search-images', requireAuth, async (req, res) =>
1029 {
1030 const query = String(req.query.query || '').trim();
1031 if (!query) return res.status(400).json({ error: 'query is required.' });
1032 if (query.length < 2) return res.status(400).json({ error: 'query must be at least 2 characters.' });
1033
1034 const { config, roots } = loadConfigAndRoots();
1035 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
1036 .filter((rootPath) =>
1037 {
1038 try
1039 {
1040 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
1041 } catch
1042 {
1043 return false;
1044 }
1045 });
1046
1047 const { results, scannedFiles, truncated } = await searchImagesWithThumbnailsInRoots(
1048 query,
1049 readableRoots,
1050 req.query.limit,
1051 );
1052
1053 res.json({
1054 query,
1055 results,
1056 scannedFiles,
1057 truncated,
1058 });
1059 });
1060
923 1061 // ---------------------------------------------------------------------------
924 1062 // GET /api/files/meta?file=<absolute-path>
925 1063 // Returns file metadata from the DB. Lazily computes SHA-256 when missing.
@@ -273,6 +273,16 @@ function fuzzyMatchScore (needle, haystack)
273 return 700 + compactness + startBonus - gapPenalty;
273 return 700 + compactness + startBonus - gapPenalty;
274}
274}
275
275
276const SEARCHABLE_IMAGE_EXTS = new Set([
277 '.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.svg', '.avif', '.ico', '.tif', '.tiff',
278]);
279
280function isSearchableImageFileName (name)
281{
282 const ext = path.extname(String(name || '')).toLowerCase();
283 return SEARCHABLE_IMAGE_EXTS.has(ext);
284}
285
276function searchFilesInRoots (query, roots, maxResults)
286function searchFilesInRoots (query, roots, maxResults)
277{
287{
278 const limit = Math.max(1, Math.min(500, Number(maxResults) || 200));
288 const limit = Math.max(1, Math.min(500, Number(maxResults) || 200));
@@ -343,6 +353,97 @@ function searchFilesInRoots (query, roots, maxResults)
343 return results.slice(0, limit);
353 return results.slice(0, limit);
344}
354}
345
355
356async function searchImagesWithThumbnailsInRoots (query, roots, maxResults)
357{
358 const limit = Math.max(1, Math.min(120, Number(maxResults) || 60));
359 const maxScannedFiles = 25000;
360 const results = [];
361 const visitedDirs = new Set();
362 let scannedFiles = 0;
363 let truncated = false;
364
365 for (const root of roots)
366 {
367 if (results.length >= limit || scannedFiles >= maxScannedFiles) break;
368
369 const rootPath = path.resolve(root);
370 const stack = [rootPath];
371
372 while (stack.length)
373 {
374 if (results.length >= limit || scannedFiles >= maxScannedFiles) break;
375
376 const dir = stack.pop();
377 if (!dir) continue;
378 const dirKey = path.resolve(dir);
379 if (visitedDirs.has(dirKey)) continue;
380 visitedDirs.add(dirKey);
381
382 let entries;
383 try
384 {
385 entries = fs.readdirSync(dir, { withFileTypes: true });
386 } catch
387 {
388 continue;
389 }
390
391 for (const entry of entries)
392 {
393 if (results.length >= limit || scannedFiles >= maxScannedFiles) break;
394
395 const fullPath = path.join(dir, entry.name);
396 if (entry.isDirectory())
397 {
398 stack.push(fullPath);
399 continue;
400 }
401 if (!entry.isFile()) continue;
402
403 scannedFiles += 1;
404 if (!isSearchableImageFileName(entry.name)) continue;
405
406 const relativePath = path.relative(rootPath, fullPath);
407 const score = fuzzyMatchScore(query, entry.name)
408 ?? fuzzyMatchScore(query, relativePath);
409 if (score == null) continue;
410
411 // Only include files that already have a ready thumbnail.
412 const thumb = await getCachedThumbnailInfo(fullPath);
413 if (!thumb) continue;
414
415 let stat = null;
416 try { stat = fs.statSync(fullPath); } catch { /* ignore disappearing files */ }
417
418 results.push({
419 name: entry.name,
420 path: fullPath,
421 dir: path.dirname(fullPath),
422 rootPath,
423 relativePath,
424 size: stat ? stat.size : null,
425 mtime: stat ? stat.mtime.toISOString() : null,
426 score,
427 });
428
429 if (results.length > limit * 3)
430 {
431 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
432 results.length = limit;
433 }
434 }
435 }
436 }
437
438 if (scannedFiles >= maxScannedFiles) truncated = true;
439 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
440 return {
441 results: results.slice(0, limit),
442 scannedFiles,
443 truncated,
444 };
445}
446
346function rootAliasesFromConfig (config)
447function rootAliasesFromConfig (config)
347{
448{
348 if (!config || typeof config !== 'object') return {};
449 if (!config || typeof config !== 'object') return {};
@@ -920,6 +1021,43 @@ router.get('/search', requireAuth, (req, res) =>
920 });
1021 });
921});
1022});
922
1023
1024// ---------------------------------------------------------------------------
1025// GET /api/files/search-images?query=<text>&limit=<number>
1026// Fuzzy-searches readable roots for image files that have ready thumbnails.
1027// ---------------------------------------------------------------------------
1028router.get('/search-images', requireAuth, async (req, res) =>
1029{
1030 const query = String(req.query.query || '').trim();
1031 if (!query) return res.status(400).json({ error: 'query is required.' });
1032 if (query.length < 2) return res.status(400).json({ error: 'query must be at least 2 characters.' });
1033
1034 const { config, roots } = loadConfigAndRoots();
1035 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
1036 .filter((rootPath) =>
1037 {
1038 try
1039 {
1040 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
1041 } catch
1042 {
1043 return false;
1044 }
1045 });
1046
1047 const { results, scannedFiles, truncated } = await searchImagesWithThumbnailsInRoots(
1048 query,
1049 readableRoots,
1050 req.query.limit,
1051 );
1052
1053 res.json({
1054 query,
1055 results,
1056 scannedFiles,
1057 truncated,
1058 });
1059});
1060
923// ---------------------------------------------------------------------------
1061// ---------------------------------------------------------------------------
924// GET /api/files/meta?file=<absolute-path>
1062// GET /api/files/meta?file=<absolute-path>
925// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
1063// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
tests/files.routes.test.js +26 −0
@@ -758,6 +758,32 @@ describe('file search endpoint', () =>
758 758 });
759 759 });
760 760
761 describe('image search endpoint', () =>
762 {
763 test('GET /api/files/search-images returns thumbnailed image matches only', async () =>
764 {
765 const picsDir = path.join(rootDir, 'Pictures');
766 fs.mkdirSync(picsDir, { recursive: true });
767 fs.writeFileSync(path.join(picsDir, 'dragon-cover.jpg'), 'img');
768 fs.writeFileSync(path.join(picsDir, 'dragon-notes.txt'), 'txt');
769
770 const thumbPath = path.join(rootDir, 'thumb.webp');
771 fs.writeFileSync(thumbPath, 'thumb');
772 mockThumbPath = thumbPath;
773
774 const { status, body } = await req('GET', '/api/files/search-images?query=dragon');
775 expect(status).toBe(200);
776 expect(body.results.length).toBe(1);
777 expect(body.results[0].name).toBe('dragon-cover.jpg');
778 });
779
780 test('GET /api/files/search-images returns 400 for short queries', async () =>
781 {
782 const { status } = await req('GET', '/api/files/search-images?query=a');
783 expect(status).toBe(400);
784 });
785 });
786
761 787 describe('global favicon endpoints', () =>
762 788 {
763 789 test('GET /api/files/global-favicon returns null when unset', async () =>
@@ -758,6 +758,32 @@ describe('file search endpoint', () =>
758 });
758 });
759});
759});
760
760
761describe('image search endpoint', () =>
762{
763 test('GET /api/files/search-images returns thumbnailed image matches only', async () =>
764 {
765 const picsDir = path.join(rootDir, 'Pictures');
766 fs.mkdirSync(picsDir, { recursive: true });
767 fs.writeFileSync(path.join(picsDir, 'dragon-cover.jpg'), 'img');
768 fs.writeFileSync(path.join(picsDir, 'dragon-notes.txt'), 'txt');
769
770 const thumbPath = path.join(rootDir, 'thumb.webp');
771 fs.writeFileSync(thumbPath, 'thumb');
772 mockThumbPath = thumbPath;
773
774 const { status, body } = await req('GET', '/api/files/search-images?query=dragon');
775 expect(status).toBe(200);
776 expect(body.results.length).toBe(1);
777 expect(body.results[0].name).toBe('dragon-cover.jpg');
778 });
779
780 test('GET /api/files/search-images returns 400 for short queries', async () =>
781 {
782 const { status } = await req('GET', '/api/files/search-images?query=a');
783 expect(status).toBe(400);
784 });
785});
786
761describe('global favicon endpoints', () =>
787describe('global favicon endpoints', () =>
762{
788{
763 test('GET /api/files/global-favicon returns null when unset', async () =>
789 test('GET /api/files/global-favicon returns null when unset', async () =>