BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

Cursor Optimisation pass
timfa Tim Falken · pushed by timfa · 5 months ago
7e6dfc52 History
files.js 74.2 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const path = require('path');
5const fs = require('fs');
6const crypto = require('crypto');
7const multer = require('multer');
8const router = express.Router();
9
10const { getDb } = require('../db');
11const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
12const { requireAuth } = require('../auth');
13const {
14 getCachedThumbnailInfo,
15 getFilesWithThumbnailsInDir,
16 getFolderIconSourceFile,
17 setFolderIconAssignment,
18 getThumbnailManifestSourcePathSet,
19 THUMB_HTTP_MAX_AGE_SEC,
20} = require('../thumbnail-cache');
21const {
22 searchFiles,
23 deleteIndexPath,
24 deleteIndexUnder,
25 rewriteIndexPaths,
26 reindexDirectoryTree,
27} = require('../search-index');
28const { logError } = require('../logger');
29const { renderImageSubtitleFrame, renderImageSubtitleFramesInRange } = require('../image-subtitles');
30const { appendSubtitleDebugEntries, SUBTITLE_DEBUG_LOG_DIR } = require('../subtitle-debug-log');
31const { buildZip } = require('./share');
32const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
33const { enqueueFileHash } = require('../file-hash-queue');
34
35// ---------------------------------------------------------------------------
36// Multer storage — files are staged into temporary files and only promoted
37// to their final names after the full stream arrives.
38// ---------------------------------------------------------------------------
39function makeTempUploadPath (dir, originalName)
40{
41 const safeName = path.basename(String(originalName || 'upload'));
42 const suffix = crypto.randomUUID();
43 return path.join(dir, `.${safeName}.upload-${suffix}.part`);
44}
45
46function unlinkIfExists (targetPath, cb)
47{
48 fs.unlink(targetPath, (err) =>
49 {
50 if (!err || err.code === 'ENOENT') return cb(null);
51 cb(err);
52 });
53}
54
55function promoteUploadedFile (tempPath, finalPath, cb)
56{
57 fs.rename(tempPath, finalPath, cb);
58}
59
60const storage = {
61 _handleFile (req, file, cb)
62 {
63 if (!req._uploadDir)
64 {
65 cb(new Error('Upload directory is not set.'));
66 return;
67 }
68
69 const finalName = path.basename(String(file.originalname || 'upload'));
70 const finalPath = path.join(req._uploadDir, finalName);
71 const tempPath = makeTempUploadPath(req._uploadDir, finalName);
72 const out = fs.createWriteStream(tempPath, { flags: 'wx' });
73
74 let settled = false;
75 let cleaned = false;
76
77 const detach = () =>
78 {
79 req.off('aborted', onAbort);
80 req.off('close', onClose);
81 file.stream.off('error', onStreamError);
82 out.off('error', onWriteError);
83 out.off('finish', onFinish);
84 };
85
86 const stopPiping = () =>
87 {
88 // Prevent late file stream chunks from writing into a destroyed stream.
89 file.stream.unpipe(out);
90 if (typeof file.stream.resume === 'function') file.stream.resume();
91 };
92
93 const cleanup = (done) =>
94 {
95 if (cleaned) return done(null);
96 cleaned = true;
97 unlinkIfExists(tempPath, done);
98 };
99
100 const fail = (err) =>
101 {
102 if (settled) return;
103 settled = true;
104 stopPiping();
105 detach();
106
107 const finishFailure = () =>
108 {
109 cleanup((cleanupErr) => cb(cleanupErr || err));
110 };
111
112 if (out.destroyed || out.writableEnded)
113 {
114 finishFailure();
115 return;
116 }
117
118 out.end(finishFailure);
119 };
120
121 const succeed = () =>
122 {
123 if (settled) return;
124 settled = true;
125 detach();
126 cb(null, {
127 destination: req._uploadDir,
128 filename: finalName,
129 originalname: file.originalname,
130 path: finalPath,
131 size: out.bytesWritten,
132 });
133 };
134
135 const onAbort = () => fail(new Error('Upload aborted.'));
136 const onClose = () =>
137 {
138 if (!req.complete) onAbort();
139 };
140 const onStreamError = (err) => fail(err);
141 const onWriteError = (err) => fail(err);
142 const onFinish = () =>
143 {
144 if (req.aborted || !req.complete)
145 {
146 fail(new Error('Upload aborted.'));
147 return;
148 }
149
150 promoteUploadedFile(tempPath, finalPath, (err) =>
151 {
152 if (err)
153 {
154 fail(err);
155 return;
156 }
157 succeed();
158 });
159 };
160
161 req.on('aborted', onAbort);
162 req.on('close', onClose);
163 file.stream.on('error', onStreamError);
164 out.on('error', onWriteError);
165 out.on('finish', onFinish);
166 file.stream.pipe(out);
167 },
168
169 _removeFile (req, file, cb)
170 {
171 unlinkIfExists(file.path, cb);
172 },
173};
174
175const upload = multer({
176 storage,
177 limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB
178});
179
180function parseOctalMode (rawValue, fallback)
181{
182 const trimmed = String(rawValue || '').trim();
183 if (!trimmed) return fallback;
184 if (!/^[0-7]{3,4}$/.test(trimmed)) return fallback;
185 const parsed = Number.parseInt(trimmed, 8);
186 if (!Number.isInteger(parsed) || parsed < 0 || parsed > 0o7777) return fallback;
187 return parsed;
188}
189
190function envFlagEnabled (name)
191{
192 const value = String(process.env[name] || '').trim().toLowerCase();
193 return value === '1' || value === 'true' || value === 'yes' || value === 'on';
194}
195
196function applyListAccessChmod (startDir)
197{
198 const dirMode = parseOctalMode(process.env.FILEMANAGER_LIST_ACCESS_CHMOD_DIR_MODE, 0o777);
199 const fileMode = parseOctalMode(process.env.FILEMANAGER_LIST_ACCESS_CHMOD_FILE_MODE, 0o666);
200 const rootDir = path.resolve(startDir);
201
202 let rootStat;
203 try
204 {
205 rootStat = fs.lstatSync(rootDir);
206 } catch
207 {
208 return;
209 }
210
211 if (rootStat.isSymbolicLink()) return;
212
213 try
214 {
215 fs.chmodSync(rootDir, rootStat.isDirectory() ? dirMode : fileMode);
216 } catch
217 {
218 // Continue best-effort; listing should still work when possible.
219 }
220
221 if (!rootStat.isDirectory()) return;
222
223 let entries = [];
224 try
225 {
226 entries = fs.readdirSync(rootDir, { withFileTypes: true });
227 } catch
228 {
229 return;
230 }
231
232 for (const entry of entries)
233 {
234 const childPath = path.join(rootDir, entry.name);
235
236 let childStat;
237 try
238 {
239 childStat = fs.lstatSync(childPath);
240 } catch
241 {
242 continue;
243 }
244
245 if (childStat.isSymbolicLink()) continue;
246
247 try
248 {
249 fs.chmodSync(childPath, childStat.isDirectory() ? dirMode : fileMode);
250 } catch
251 {
252 // Continue best-effort; listing should still work when possible.
253 }
254 }
255}
256
257// ---------------------------------------------------------------------------
258// Helpers
259// ---------------------------------------------------------------------------
260
261function effectivePaths ()
262{
263 return getEffectivePaths(loadConfig().paths || []);
264}
265
266const META_BATCH_SIZE = 400;
267
268function loadUploadedAtByPaths (db, paths)
269{
270 const map = new Map();
271 const unique = [...new Set(paths.map((p) => String(p || '')).filter(Boolean))];
272 for (let i = 0; i < unique.length; i += META_BATCH_SIZE)
273 {
274 const chunk = unique.slice(i, i + META_BATCH_SIZE);
275 const placeholders = chunk.map(() => '?').join(', ');
276 const rows = db.prepare(`SELECT file_path, uploaded_at FROM file_meta WHERE file_path IN (${placeholders})`)
277 .all(chunk);
278 for (const row of rows)
279 {
280 map.set(row.file_path, String(row.uploaded_at || '').trim());
281 }
282 }
283 return map;
284}
285
286function persistMissingUploadedAt (db, rows)
287{
288 if (!rows.length) return;
289
290 const stmt = db.prepare(`
291 INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at)
292 VALUES (?, ?, ?, ?, ?)
293 ON CONFLICT(file_path) DO UPDATE SET
294 uploaded_at = COALESCE(NULLIF(file_meta.uploaded_at, ''), excluded.uploaded_at)
295 `);
296 for (const row of rows) stmt.run(row);
297}
298
299function setUserLastDir (username, dirPath)
300{
301 if (!username) return;
302 const db = getDb();
303 db.prepare(`
304 INSERT INTO user_last_navigation (username, last_dir, updated_at)
305 VALUES (?, ?, ?)
306 ON CONFLICT(username) DO UPDATE SET
307 last_dir = excluded.last_dir,
308 updated_at = excluded.updated_at
309 `).run([String(username), String(dirPath || ''), Date.now()]);
310}
311
312function getUserLastDir (username)
313{
314 if (!username) return null;
315 const db = getDb();
316 const row = db.prepare('SELECT last_dir FROM user_last_navigation WHERE username = ?').get([String(username)]);
317 const value = String(row && row.last_dir || '').trim();
318 return value || null;
319}
320
321function clearUserLastDir (username)
322{
323 if (!username) return;
324 const db = getDb();
325 db.prepare('DELETE FROM user_last_navigation WHERE username = ?').run([String(username)]);
326}
327
328/**
329 * Loads config and returns { config, roots } together so both are consistent
330 * and user-folder checks can be performed in route handlers.
331 */
332function loadConfigAndRoots ()
333{
334 const config = loadConfig();
335 return { config, roots: getEffectivePaths(config.paths || []) };
336}
337
338/**
339 * Returns true when absPath is accessible to the user (either via a
340 * configured root or their personal folder).
341 */
342function isAccessiblePath (absPath, roots, user, config)
343{
344 return resolveRootForUser(absPath, roots, user, config) !== null;
345}
346
347function readableSearchRootsForUser (user, config, roots)
348{
349 const out = [];
350 for (const root of roots)
351 {
352 const label = path.basename(root);
353 if (canRead(user, label)) out.push(root);
354 }
355
356 const personal = getUserFolderPath(config, user && user.username);
357 if (personal) out.push(personal);
358
359 // Deduplicate by resolved path.
360 const seen = new Set();
361 return out.filter((p) =>
362 {
363 const key = path.resolve(p);
364 if (seen.has(key)) return false;
365 seen.add(key);
366 return true;
367 });
368}
369
370const SEARCHABLE_IMAGE_EXTS = new Set([
371 '.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.svg', '.avif', '.ico', '.tif', '.tiff',
372]);
373
374function isSearchableImageFileName (name)
375{
376 const ext = path.extname(String(name || '')).toLowerCase();
377 return SEARCHABLE_IMAGE_EXTS.has(ext);
378}
379
380async function searchImagesWithThumbnailsInRoots (query, roots, maxResults)
381{
382 const limit = Math.max(1, Math.min(120, Number(maxResults) || 60));
383 const candidateLimit = Math.min(250, Math.max(limit * 4, 80));
384 const indexed = await searchFiles(query, roots, candidateLimit);
385 const thumbnailedPaths = await getThumbnailManifestSourcePathSet();
386
387 const results = [];
388 for (const item of indexed)
389 {
390 if (!isSearchableImageFileName(item.name)) continue;
391 if (!thumbnailedPaths.has(path.resolve(item.path))) continue;
392
393 const { score, ...rest } = item;
394 results.push(rest);
395 if (results.length >= limit) break;
396 }
397
398 return {
399 results,
400 scannedFiles: indexed.length,
401 truncated: indexed.length >= candidateLimit,
402 };
403}
404
405function rootAliasesFromConfig (config)
406{
407 if (!config || typeof config !== 'object') return {};
408 if (!config.rootAliases || typeof config.rootAliases !== 'object') return {};
409 return config.rootAliases;
410}
411
412function getFreeBytes (targetPath)
413{
414 if (typeof fs.statfsSync !== 'function') return null;
415 try
416 {
417 const stat = fs.statfsSync(targetPath);
418 if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null;
419 return stat.bavail * stat.bsize;
420 } catch
421 {
422 return null;
423 }
424}
425
426function getRecursiveSize (targetPath)
427{
428 try
429 {
430 const stat = fs.statSync(targetPath);
431 if (!stat.isDirectory()) return stat.size;
432 } catch
433 {
434 return 0;
435 }
436
437 let total = 0;
438 let entries = [];
439 try
440 {
441 entries = fs.readdirSync(targetPath, { withFileTypes: true });
442 } catch
443 {
444 return 0;
445 }
446
447 for (const entry of entries)
448 {
449 const child = path.join(targetPath, entry.name);
450 if (entry.isDirectory())
451 {
452 total += getRecursiveSize(child);
453 continue;
454 }
455 try
456 {
457 total += fs.statSync(child).size;
458 } catch
459 {
460 // Ignore files that disappear during traversal.
461 }
462 }
463
464 return total;
465}
466
467/**
468 * Verify that the user has read access to the given configured-path label.
469 * `pathLabel` is the base-name of the effective path (shown in the UI).
470 */
471function canRead (user, pathLabel)
472{
473 if (user.isAdmin) return true;
474 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
475}
476
477function canWrite (user, pathLabel)
478{
479 if (user.isAdmin) return true;
480 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
481}
482
483// ---------------------------------------------------------------------------
484// User folder helpers
485// ---------------------------------------------------------------------------
486
487/**
488 * Returns the absolute path of the user's personal folder, or null.
489 * e.g. /data/userfolders/<username>
490 */
491function getUserFolderPath (config, username)
492{
493 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
494 if (!base) return null;
495 return path.join(base, String(username));
496}
497
498function getUserFolderRootPath (config)
499{
500 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
501 if (!base) return null;
502 return path.resolve(base);
503}
504
505function existingUsernamesLowerSet ()
506{
507 const db = getDb();
508 const rows = db.prepare('SELECT username FROM users').all();
509 return new Set(rows.map((row) => String(row.username || '').toLowerCase()));
510}
511
512/**
513 * Resolves a request path against both the configured roots AND the user's
514 * personal folder. Returns { root, label, isUserFolder } or null.
515 * - isUserFolder: true when the path is inside the user's personal folder.
516 */
517function resolveRootForUser (absPath, roots, user, config)
518{
519 if (user && user.isAdmin && pathInsideResolved(absPath, SUBTITLE_DEBUG_LOG_DIR))
520 {
521 return {
522 root: SUBTITLE_DEBUG_LOG_DIR,
523 label: 'Subtitle Logs',
524 isUserFolder: false,
525 isDebugLogFolder: true,
526 };
527 }
528
529 // Regular configured roots first.
530 const matched = getAllowedRoot(absPath, roots);
531 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
532
533 // Check user personal folder.
534 if (!user || !user.username) return null;
535 const userFolder = getUserFolderPath(config, user.username);
536 if (!userFolder) return null;
537
538 const resolved = path.resolve(absPath);
539 const resolvedFolder = path.resolve(userFolder);
540 if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep))
541 {
542 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
543 }
544
545 // Admins can access orphaned user folders (folders without a matching account).
546 if (user && user.isAdmin)
547 {
548 const userFolderRoot = getUserFolderRootPath(config);
549 if (!userFolderRoot) return null;
550
551 const relative = path.relative(userFolderRoot, resolved);
552 if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
553
554 const parts = relative.split(path.sep).filter(Boolean);
555 if (!parts.length) return null;
556
557 const folderName = parts[0];
558 const usernames = existingUsernamesLowerSet();
559 if (usernames.has(String(folderName).toLowerCase())) return null;
560
561 const orphanRoot = path.join(userFolderRoot, folderName);
562 return {
563 root: orphanRoot,
564 label: folderName,
565 isUserFolder: false,
566 isOrphanUserFolder: true,
567 };
568 }
569
570 return null;
571}
572
573/**
574 * Checks whether the user has READ access to the resolved root info object
575 * returned by resolveRootForUser.
576 */
577function canReadInfo (user, info)
578{
579 if (!info) return false;
580 if (info.isUserFolder) return true; // owner always has full access
581 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
582 if (info.isDebugLogFolder) return !!(user && user.isAdmin);
583 return canRead(user, info.label);
584}
585
586/**
587 * Checks whether the user has WRITE access to the resolved root info object.
588 */
589function canWriteInfo (user, info)
590{
591 if (!info) return false;
592 if (info.isUserFolder) return true;
593 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
594 if (info.isDebugLogFolder) return !!(user && user.isAdmin);
595 return canWrite(user, info.label);
596}
597
598/**
599 * Returns the size limit (bytes) for the user's personal folder, or null = unlimited.
600 */
601function getUserFolderSizeLimit (config)
602{
603 const lim = Number(config.userFolderSizeLimit);
604 return Number.isFinite(lim) && lim > 0 ? lim : null;
605}
606
607/**
608 * Returns an error message if adding `addedBytes` to the user's folder would
609 * exceed the size limit, or null if within limits.
610 */
611function checkUserFolderSizeLimit (config, username, addedBytes)
612{
613 const limit = getUserFolderSizeLimit(config);
614 if (!limit) return null;
615 const userFolder = getUserFolderPath(config, username);
616 if (!userFolder) return null;
617 const currentSize = getRecursiveSize(userFolder);
618 if (currentSize + addedBytes > limit)
619 {
620 return `Your personal folder is full (limit ${formatBytesServer(limit)}, used ${formatBytesServer(currentSize)}).`;
621 }
622 return null;
623}
624
625function formatBytesServer (bytes)
626{
627 if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
628 if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
629 if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
630 return `${bytes} B`;
631}
632
633/**
634 * Given an absolute path and the effective-paths list, return
635 * { root, label } where label is the base-name of the root, or null.
636 */
637function resolveRoot (absPath, roots)
638{
639 const matchedRoot = getAllowedRoot(absPath, roots);
640 if (!matchedRoot) return null;
641 return { root: matchedRoot, label: path.basename(matchedRoot) };
642}
643
644function sameResolvedPath (a, b)
645{
646 return path.resolve(String(a || '')) === path.resolve(String(b || ''));
647}
648
649function pathInsideResolved (child, root)
650{
651 const relative = path.relative(path.resolve(root), path.resolve(child));
652 return relative === '' || (!!relative && !relative.startsWith('..') && !path.isAbsolute(relative));
653}
654
655function uploadedAtFromStat (stat)
656{
657 if (!stat || typeof stat !== 'object') return null;
658 const birthtimeMs = Number(stat.birthtimeMs);
659 const ctimeMs = Number(stat.ctimeMs);
660 const mtimeMs = Number(stat.mtimeMs);
661
662 const chosenMs = (Number.isFinite(birthtimeMs) && birthtimeMs > 0)
663 ? birthtimeMs
664 : (Number.isFinite(ctimeMs) && ctimeMs > 0)
665 ? ctimeMs
666 : (Number.isFinite(mtimeMs) && mtimeMs > 0)
667 ? mtimeMs
668 : null;
669
670 if (!Number.isFinite(chosenMs) || chosenMs <= 0) return null;
671 return new Date(chosenMs).toISOString();
672}
673
674function rewriteMetaPaths (fromPath, toPath)
675{
676 const db = getDb();
677 const columns = db.prepare('PRAGMA table_info(file_meta)').all()
678 .map((col) => String(col.name || ''))
679 .filter(Boolean);
680
681 if (!columns.includes('file_path')) return;
682
683 const quotedColumns = columns.map((col) => `"${col}"`).join(', ');
684 const rows = db.prepare(`SELECT ${quotedColumns} FROM file_meta WHERE file_path = ? OR file_path LIKE ?`)
685 .all([fromPath, fromPath + path.sep + '%']);
686
687 if (!rows.length) return;
688
689 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
690 const placeholders = columns.map(() => '?').join(', ');
691 const updateAssignments = columns
692 .filter((col) => col !== 'file_path')
693 .map((col) => `"${col}" = excluded."${col}"`)
694 .join(',\n ');
695 const upsert = db.prepare(`
696 INSERT INTO file_meta (${quotedColumns})
697 VALUES (${placeholders})
698 ON CONFLICT(file_path) DO UPDATE SET
699 ${updateAssignments}
700 `);
701
702 for (const row of rows)
703 {
704 const nextPath = row.file_path === fromPath
705 ? toPath
706 : toPath + row.file_path.slice(fromPath.length);
707 del.run([row.file_path]);
708 const movedRow = {
709 ...row,
710 file_path: nextPath,
711 };
712 upsert.run(columns.map((col) => movedRow[col]));
713 }
714}
715
716function parseJsonArray (raw)
717{
718 try
719 {
720 const value = JSON.parse(raw || '[]');
721 return Array.isArray(value) ? value : [];
722 } catch
723 {
724 return [];
725 }
726}
727
728function parseJsonObject (raw)
729{
730 try
731 {
732 const value = JSON.parse(raw || '{}');
733 if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
734 return value;
735 } catch
736 {
737 return {};
738 }
739}
740
741function watchStatusForProgress (progress)
742{
743 if (!Number.isFinite(progress) || progress < 0) return null;
744 if (progress >= 0.7) return 'fully';
745 if (progress >= 0.05) return 'partway';
746 return null;
747}
748
749function normalisedWatchedStatus (value)
750{
751 const status = String(value || '').toLowerCase();
752 return status === 'fully' || status === 'partway' ? status : null;
753}
754
755function splitNameExt (name)
756{
757 const dot = String(name || '').lastIndexOf('.');
758 if (dot <= 0) return { stem: String(name || ''), ext: '' };
759 return {
760 stem: String(name).slice(0, dot),
761 ext: String(name).slice(dot),
762 };
763}
764
765function pickNumberedPath (dir, requestedName)
766{
767 const parsed = splitNameExt(requestedName);
768 const stem = parsed.stem || 'file';
769 const ext = parsed.ext || '';
770 let index = 1;
771
772 while (index <= 10000)
773 {
774 const candidateName = `${stem} (${index})${ext}`;
775 const candidatePath = path.join(dir, candidateName);
776 if (!fs.existsSync(candidatePath)) return candidatePath;
777 index++;
778 }
779
780 throw new Error('Could not generate a free destination name.');
781}
782
783function removePathRecursive (targetPath)
784{
785 const stat = fs.lstatSync(targetPath);
786 if (stat.isDirectory())
787 {
788 fs.rmSync(targetPath, { recursive: true, force: true });
789 } else
790 {
791 fs.unlinkSync(targetPath);
792 }
793}
794
795function movePathWithFallback (from, dest)
796{
797 const stat = fs.lstatSync(from);
798 try
799 {
800 fs.renameSync(from, dest);
801 return 'rename';
802 } catch (err)
803 {
804 try
805 {
806 if (stat.isDirectory())
807 {
808 fs.cpSync(from, dest, { recursive: true, force: true, preserveTimestamps: true });
809 } else
810 {
811 fs.copyFileSync(from, dest);
812 }
813 fs.rmSync(from, { recursive: true, force: true });
814 return 'copy-delete';
815 } catch (fallbackErr)
816 {
817 throw fallbackErr || err;
818 }
819 }
820}
821
822// ---------------------------------------------------------------------------
823// GET /api/files/roots
824// Returns the effective configured paths the user can read.
825// Also injects the user's personal folder when userPath is configured.
826// ---------------------------------------------------------------------------
827router.get('/roots', requireAuth, (req, res) =>
828{
829 const config = loadConfig();
830 const roots = getEffectivePaths(config.paths || []);
831 const rootAliases = rootAliasesFromConfig(config);
832
833 const readable = roots
834 .filter(r => canRead(req.user, path.basename(r)))
835 .map(r =>
836 {
837 const originalName = path.basename(r);
838 const alias = String(rootAliases[path.resolve(r)] || '').trim();
839 return {
840 label: alias || originalName,
841 path: r,
842 originalName,
843 alias: alias || null,
844 };
845 });
846
847 // Inject the user's personal folder when a userPath is configured.
848 if (req.user && req.user.username)
849 {
850 const userFolder = getUserFolderPath(config, req.user.username);
851 if (userFolder)
852 {
853 try { fs.mkdirSync(userFolder, { recursive: true }); } catch { /* non-fatal */ }
854 readable.unshift({
855 label: 'My Folder',
856 path: userFolder,
857 originalName: req.user.username,
858 alias: 'My Folder',
859 isUserFolder: true,
860 });
861 }
862 }
863
864 let lastDir = getUserLastDir(req.user && req.user.username);
865 if (lastDir)
866 {
867 const info = resolveRootForUser(lastDir, roots, req.user, config);
868 const hasAccess = !!(info && canReadInfo(req.user, info));
869 let isDir = false;
870 if (hasAccess)
871 {
872 try
873 {
874 isDir = fs.statSync(lastDir).isDirectory();
875 } catch
876 {
877 isDir = false;
878 }
879 }
880
881 if (!hasAccess || !isDir)
882 {
883 clearUserLastDir(req.user && req.user.username);
884 lastDir = null;
885 }
886 }
887
888 res.json({ roots: readable, lastDir });
889});
890
891// ---------------------------------------------------------------------------
892// GET /api/files/root-access?rootPath=<absolute-root-path>
893// Returns users that can access a configured root and their mode (R / R+W).
894// ---------------------------------------------------------------------------
895router.get('/root-access', requireAuth, (req, res) =>
896{
897 const rootPath = String(req.query.rootPath || '').trim();
898 if (!rootPath)
899 {
900 return res.status(400).json({ error: 'rootPath is required.' });
901 }
902
903 const config = loadConfig();
904 const roots = getEffectivePaths(config.paths || []);
905 const info = resolveRoot(rootPath, roots);
906 if (!info) return res.status(403).json({ error: 'Access denied.' });
907 if (!sameResolvedPath(rootPath, info.root))
908 {
909 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
910 }
911 if (!canRead(req.user, info.label))
912 {
913 return res.status(403).json({ error: 'Access denied.' });
914 }
915
916 const db = getDb();
917 const rows = db.prepare('SELECT username, is_admin, permissions FROM users').all();
918 const users = [];
919
920 for (const row of rows)
921 {
922 if (row.is_admin === 1)
923 {
924 users.push({ username: row.username, mode: 'R+W' });
925 continue;
926 }
927
928 let permissions = {};
929 try
930 {
931 permissions = JSON.parse(row.permissions || '{}');
932 } catch
933 {
934 permissions = {};
935 }
936
937 const perm = permissions[info.label];
938 if (!perm || typeof perm !== 'object') continue;
939 const canWriteRoot = !!perm.write;
940 const canReadRoot = !!perm.read || canWriteRoot;
941 if (!canReadRoot) continue;
942 users.push({ username: row.username, mode: canWriteRoot ? 'R+W' : 'R' });
943 }
944
945 users.sort((a, b) =>
946 {
947 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
948 const byMode = modeRank(a.mode) - modeRank(b.mode);
949 if (byMode !== 0) return byMode;
950 return String(a.username).localeCompare(String(b.username));
951 });
952
953 const rootAliases = rootAliasesFromConfig(config);
954 const alias = String(rootAliases[path.resolve(info.root)] || '').trim();
955 res.json({
956 root: {
957 path: info.root,
958 label: alias || info.label,
959 originalName: info.label,
960 alias: alias || null,
961 },
962 users,
963 });
964});
965
966// ---------------------------------------------------------------------------
967// POST /api/files/root-alias
968// Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
969// Sets a display-only alias for a configured root.
970// ---------------------------------------------------------------------------
971router.post('/root-alias', requireAuth, (req, res) =>
972{
973 const rootPath = String(req.body && req.body.rootPath || '').trim();
974 const alias = String(req.body && req.body.alias || '').trim();
975 if (!rootPath || !alias)
976 {
977 return res.status(400).json({ error: 'rootPath and alias are required.' });
978 }
979
980 const roots = effectivePaths();
981 const info = resolveRoot(rootPath, roots);
982 if (!info) return res.status(403).json({ error: 'Access denied.' });
983 if (!sameResolvedPath(rootPath, info.root))
984 {
985 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
986 }
987 if (!canWrite(req.user, info.label))
988 {
989 return res.status(403).json({ error: 'Access denied.' });
990 }
991
992 const config = loadConfig();
993 const rootAliases = rootAliasesFromConfig(config);
994 const key = path.resolve(info.root);
995 if (alias === info.label)
996 {
997 delete rootAliases[key];
998 } else
999 {
1000 rootAliases[key] = alias;
1001 }
1002 config.rootAliases = rootAliases;
1003 saveConfig(config);
1004
1005 res.json({
1006 ok: true,
1007 root: {
1008 path: info.root,
1009 label: alias,
1010 originalName: info.label,
1011 alias,
1012 },
1013 });
1014});
1015
1016// ---------------------------------------------------------------------------
1017// GET /api/files/list?dir=<absolute-path>
1018// Lists files and folders in the given directory.
1019// ---------------------------------------------------------------------------
1020router.get('/list', requireAuth, async (req, res) =>
1021{
1022 const dir = req.query.dir;
1023 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1024
1025 const { config, roots } = loadConfigAndRoots();
1026 const info = resolveRootForUser(dir, roots, req.user, config);
1027 if (!info || !canReadInfo(req.user, info)) return res.status(403).json({ error: 'Access denied.' });
1028
1029 if (envFlagEnabled('FILEMANAGER_LIST_ACCESS_CHMOD'))
1030 {
1031 try
1032 {
1033 applyListAccessChmod(dir);
1034 } catch (err)
1035 {
1036 logError('Best-effort shallow chmod pass failed before directory listing.', err, { dir: String(dir || '') });
1037 }
1038 }
1039
1040 let entries;
1041 try
1042 {
1043 entries = await fs.promises.readdir(dir, { withFileTypes: true });
1044 } catch
1045 {
1046 return res.status(404).json({ error: 'Directory not found.' });
1047 }
1048
1049 const fullPaths = entries.map((e) => path.join(dir, e.name));
1050 const db = getDb();
1051 const uploadedAtByPath = loadUploadedAtByPaths(db, fullPaths);
1052 const metaUpserts = [];
1053
1054 const statResults = await Promise.all(fullPaths.map(async (fullPath) =>
1055 {
1056 try
1057 {
1058 return { fullPath, stat: await fs.promises.stat(fullPath) };
1059 } catch
1060 {
1061 return { fullPath, stat: null };
1062 }
1063 }));
1064
1065 const statByPath = new Map(statResults.map((row) => [row.fullPath, row.stat]));
1066
1067 const items = entries.map((e) =>
1068 {
1069 const fullPath = path.join(dir, e.name);
1070 const stat = statByPath.get(fullPath);
1071 let size = null;
1072 let mtime = null;
1073 let uploadedAt = null;
1074
1075 if (stat)
1076 {
1077 size = stat.size;
1078 mtime = stat.mtime.toISOString();
1079 uploadedAt = uploadedAtByPath.get(fullPath) || uploadedAtFromStat(stat) || null;
1080 if (uploadedAt && !uploadedAtByPath.has(fullPath))
1081 {
1082 metaUpserts.push([fullPath, '', '[]', '{}', uploadedAt]);
1083 }
1084 }
1085
1086 return {
1087 name: e.name,
1088 isDir: e.isDirectory(),
1089 size,
1090 mtime,
1091 uploadedAt,
1092 path: fullPath,
1093 };
1094 });
1095
1096 try
1097 {
1098 persistMissingUploadedAt(db, metaUpserts);
1099 } catch
1100 {
1101 // Non-fatal metadata persistence.
1102 }
1103
1104 try
1105 {
1106 setUserLastDir(req.user && req.user.username, dir);
1107 } catch
1108 {
1109 // Non-fatal preference persistence.
1110 }
1111
1112 res.json({ items });
1113});
1114
1115// ---------------------------------------------------------------------------
1116// GET /api/files/search?query=<text>&limit=<number>
1117// Fuzzy-searches all readable roots for files.
1118// ---------------------------------------------------------------------------
1119router.get('/search', requireAuth, async (req, res) =>
1120{
1121 const query = String(req.query.query || '').trim();
1122 if (!query) return res.status(400).json({ error: 'query is required.' });
1123
1124 const { config, roots } = loadConfigAndRoots();
1125 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
1126 .filter((rootPath) =>
1127 {
1128 try
1129 {
1130 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
1131 } catch
1132 {
1133 return false;
1134 }
1135 });
1136
1137 const results = await searchFiles(query, readableRoots, req.query.limit);
1138 res.json({
1139 query,
1140 results,
1141 });
1142});
1143
1144// ---------------------------------------------------------------------------
1145// GET /api/files/search-images?query=<text>&limit=<number>
1146// Fuzzy-searches readable roots for image files that have ready thumbnails.
1147// ---------------------------------------------------------------------------
1148router.get('/search-images', requireAuth, async (req, res) =>
1149{
1150 const query = String(req.query.query || '').trim();
1151 if (!query) return res.status(400).json({ error: 'query is required.' });
1152 if (query.length < 2) return res.status(400).json({ error: 'query must be at least 2 characters.' });
1153
1154 const { config, roots } = loadConfigAndRoots();
1155 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
1156 .filter((rootPath) =>
1157 {
1158 try
1159 {
1160 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
1161 } catch
1162 {
1163 return false;
1164 }
1165 });
1166
1167 const { results, scannedFiles, truncated } = await searchImagesWithThumbnailsInRoots(
1168 query,
1169 readableRoots,
1170 req.query.limit,
1171 );
1172
1173 res.json({
1174 query,
1175 results,
1176 scannedFiles,
1177 truncated,
1178 });
1179});
1180
1181// ---------------------------------------------------------------------------
1182// GET /api/files/meta?file=<absolute-path>
1183// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
1184// ---------------------------------------------------------------------------
1185router.get('/meta', requireAuth, async (req, res) =>
1186{
1187 const file = req.query.file;
1188 if (!file) return res.status(400).json({ error: 'file is required.' });
1189
1190 const { config, roots } = loadConfigAndRoots();
1191 const info = resolveRootForUser(file, roots, req.user, config);
1192 if (!info || !canReadInfo(req.user, info))
1193 {
1194 return res.status(403).json({ error: 'Access denied.' });
1195 }
1196
1197 let stat;
1198 try
1199 {
1200 stat = fs.statSync(file);
1201 } catch
1202 {
1203 return res.status(404).json({ error: 'File not found.' });
1204 }
1205
1206 const db = getDb();
1207 let meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
1208 let uploadedAt = meta ? String(meta.uploaded_at || '').trim() : '';
1209 if (!uploadedAt)
1210 {
1211 uploadedAt = uploadedAtFromStat(stat) || '';
1212 if (uploadedAt)
1213 {
1214 db.prepare(`
1215 INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at)
1216 VALUES (?, ?, ?, ?, ?)
1217 ON CONFLICT(file_path) DO UPDATE SET
1218 uploaded_at = COALESCE(NULLIF(file_meta.uploaded_at, ''), excluded.uploaded_at)
1219 `).run([file, '', '[]', '{}', uploadedAt]);
1220
1221 meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
1222 }
1223 }
1224
1225 let sha256 = meta ? (meta.sha256 || null) : null;
1226 if (!sha256 && !stat.isDirectory())
1227 {
1228 enqueueFileHash(file);
1229 }
1230
1231 res.json({
1232 name: path.basename(file),
1233 size: stat.size,
1234 mtime: stat.mtime.toISOString(),
1235 uploadedAt: uploadedAt || null,
1236 uploader: meta ? meta.uploader : '',
1237 downloaders: meta ? parseJsonArray(meta.downloaders) : [],
1238 watchedBy: meta ? parseJsonObject(meta.watched_by) : {},
1239 sha256: sha256 || null,
1240 });
1241});
1242
1243// ---------------------------------------------------------------------------
1244// GET /api/files/duplicates?file=<absolute-path>
1245// Returns other files with the same SHA-256 hash that the user can access.
1246// ---------------------------------------------------------------------------
1247router.get('/duplicates', requireAuth, (req, res) =>
1248{
1249 const file = req.query.file;
1250 if (!file) return res.status(400).json({ error: 'file is required.' });
1251
1252 const { config, roots } = loadConfigAndRoots();
1253 const info = resolveRootForUser(file, roots, req.user, config);
1254 if (!info || !canReadInfo(req.user, info))
1255 {
1256 return res.status(403).json({ error: 'Access denied.' });
1257 }
1258
1259 const db = getDb();
1260 const row = db.prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([file]);
1261 const hash = row ? (row.sha256 || null) : null;
1262 if (!hash)
1263 {
1264 enqueueFileHash(file);
1265 return res.json({ duplicates: [] });
1266 }
1267
1268 // All other files sharing the same hash.
1269 const candidates = db.prepare(
1270 'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',
1271 ).all([hash, file]);
1272
1273 const duplicates = [];
1274 for (const { file_path } of candidates)
1275 {
1276 // Only return files inside a root the user can access and that still exist on disk.
1277 const dupInfo = resolveRootForUser(file_path, roots, req.user, config);
1278 if (!dupInfo || !canReadInfo(req.user, dupInfo)) continue;
1279 if (!fs.existsSync(file_path)) continue;
1280
1281 const rel = path.relative(dupInfo.root, file_path);
1282 const relativePath = rel && rel !== '' ? rel : path.basename(file_path);
1283
1284 duplicates.push({
1285 path: file_path,
1286 name: path.basename(file_path),
1287 dir: path.dirname(file_path),
1288 rootPath: dupInfo.root,
1289 relativePath,
1290 });
1291 }
1292
1293 res.json({ duplicates });
1294});
1295
1296// ---------------------------------------------------------------------------
1297// GET /api/files/space?dir=<absolute-path>
1298// Returns recursive used bytes for dir and available bytes on its root fs.
1299// ---------------------------------------------------------------------------
1300router.get('/space', requireAuth, (req, res) =>
1301{
1302 const dir = req.query.dir;
1303 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1304
1305 const { config, roots } = loadConfigAndRoots();
1306 const info = resolveRootForUser(dir, roots, req.user, config);
1307 if (!info || !canReadInfo(req.user, info))
1308 {
1309 return res.status(403).json({ error: 'Access denied.' });
1310 }
1311
1312 if (!fs.existsSync(dir))
1313 {
1314 return res.status(404).json({ error: 'Path not found.' });
1315 }
1316
1317 const usedBytes = getRecursiveSize(dir);
1318 const freeBytes = getFreeBytes(info.root);
1319 const userLimitBytes = info.isUserFolder ? getUserFolderSizeLimit(config) : null;
1320 const userFreeBytes = userLimitBytes == null ? null : Math.max(0, userLimitBytes - usedBytes);
1321 res.json({
1322 usedBytes,
1323 freeBytes,
1324 userLimitBytes,
1325 userFreeBytes,
1326 rootPath: info.root,
1327 rootLabel: info.label,
1328 });
1329});
1330
1331// ---------------------------------------------------------------------------
1332// GET /api/files/download?file=<absolute-path>
1333// Streams the file to the client; records the download.
1334// ---------------------------------------------------------------------------
1335router.get('/download', requireAuth, (req, res) =>
1336{
1337 const file = req.query.file;
1338 if (!file) return res.status(400).json({ error: 'file is required.' });
1339
1340 const { config, roots } = loadConfigAndRoots();
1341 const info = resolveRootForUser(file, roots, req.user, config);
1342 if (!info || !canReadInfo(req.user, info))
1343 {
1344 return res.status(403).json({ error: 'Access denied.' });
1345 }
1346
1347 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1348 {
1349 return res.status(404).json({ error: 'File not found.' });
1350 }
1351
1352 // Record download
1353 const db = getDb();
1354 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
1355 const uploadedAt = (() =>
1356 {
1357 try { return uploadedAtFromStat(fs.statSync(file)); }
1358 catch { return null; }
1359 })();
1360 if (meta)
1361 {
1362 const downloaders = parseJsonArray(meta.downloaders);
1363 if (!downloaders.includes(req.user.username))
1364 {
1365 downloaders.push(req.user.username);
1366 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
1367 .run([JSON.stringify(downloaders), file]);
1368 }
1369 } else
1370 {
1371 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at) VALUES (?, ?, ?, ?, ?)')
1372 .run([file, '', JSON.stringify([req.user.username]), '{}', uploadedAt]);
1373 }
1374
1375 res.download(file, path.basename(file));
1376});
1377
1378// ---------------------------------------------------------------------------
1379// POST /api/files/watched-statuses
1380// Body: { filePaths: [<absolute-path>, ...] }
1381// Returns per-path watched status for the authenticated user.
1382// ---------------------------------------------------------------------------
1383router.post('/watched-statuses', requireAuth, (req, res) =>
1384{
1385 const rawPaths = req.body && Array.isArray(req.body.filePaths) ? req.body.filePaths : null;
1386 if (!rawPaths)
1387 {
1388 return res.status(400).json({ error: 'filePaths array is required.' });
1389 }
1390
1391 const paths = rawPaths
1392 .map((p) => String(p || '').trim())
1393 .filter(Boolean)
1394 .slice(0, 500);
1395
1396 const { config, roots } = loadConfigAndRoots();
1397 const db = getDb();
1398 const statuses = {};
1399 const selectMeta = db.prepare('SELECT watched_by FROM file_meta WHERE file_path = ?');
1400
1401 for (const filePath of paths)
1402 {
1403 const info = resolveRootForUser(filePath, roots, req.user, config);
1404 if (!info || !canReadInfo(req.user, info)) continue;
1405
1406 let stat;
1407 try
1408 {
1409 stat = fs.statSync(filePath);
1410 } catch
1411 {
1412 continue;
1413 }
1414 if (stat.isDirectory()) continue;
1415
1416 const row = selectMeta.get([filePath]);
1417 const watchedBy = parseJsonObject(row && row.watched_by);
1418 const status = normalisedWatchedStatus(watchedBy[req.user.username]);
1419 if (status) statuses[filePath] = status;
1420 }
1421
1422 res.json({ statuses });
1423});
1424
1425// ---------------------------------------------------------------------------
1426// POST /api/files/watch-progress
1427// Body: { filePath: <absolute-path>, progress: <0..1> }
1428// Records per-user video watch state for sidebar display.
1429// ---------------------------------------------------------------------------
1430router.post('/watch-progress', requireAuth, (req, res) =>
1431{
1432 const filePath = String(req.body && req.body.filePath || '').trim();
1433 const progress = Number(req.body && req.body.progress);
1434 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
1435
1436 const status = watchStatusForProgress(progress);
1437 if (!status)
1438 {
1439 return res.json({ ok: true, updated: false });
1440 }
1441
1442 const { config, roots } = loadConfigAndRoots();
1443 const info = resolveRootForUser(filePath, roots, req.user, config);
1444 if (!info || !canReadInfo(req.user, info))
1445 {
1446 return res.status(403).json({ error: 'Access denied.' });
1447 }
1448
1449 let fileStat;
1450 try
1451 {
1452 fileStat = fs.statSync(filePath);
1453 } catch
1454 {
1455 return res.status(404).json({ error: 'File not found.' });
1456 }
1457
1458 if (fileStat.isDirectory())
1459 {
1460 return res.status(404).json({ error: 'File not found.' });
1461 }
1462
1463 const db = getDb();
1464 const row = db.prepare('SELECT uploader, downloaders, watched_by FROM file_meta WHERE file_path = ?').get([filePath]);
1465 const watchedBy = parseJsonObject(row && row.watched_by);
1466 const prev = String(watchedBy[req.user.username] || '').toLowerCase();
1467 const next = prev === 'fully' ? 'fully' : status;
1468 if (prev === next)
1469 {
1470 return res.json({ ok: true, updated: false, status: next });
1471 }
1472
1473 watchedBy[req.user.username] = next;
1474 if (row)
1475 {
1476 db.prepare('UPDATE file_meta SET watched_by = ? WHERE file_path = ?')
1477 .run([JSON.stringify(watchedBy), filePath]);
1478 } else
1479 {
1480 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at) VALUES (?, ?, ?, ?, ?)')
1481 .run([filePath, '', '[]', JSON.stringify(watchedBy), uploadedAtFromStat(fileStat)]);
1482 }
1483
1484 res.json({ ok: true, updated: true, status: next });
1485});
1486
1487// ---------------------------------------------------------------------------
1488// POST /api/files/video-stream
1489// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
1490// ---------------------------------------------------------------------------
1491router.post('/video-stream', requireAuth, async (req, res, next) =>
1492{
1493 try
1494 {
1495 const filePath = String(req.body?.filePath || '').trim();
1496 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
1497
1498 const { config, roots } = loadConfigAndRoots();
1499 const info = resolveRootForUser(filePath, roots, req.user, config);
1500 if (!info || !canReadInfo(req.user, info))
1501 {
1502 return res.status(403).json({ error: 'Access denied.' });
1503 }
1504
1505 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1506 {
1507 return res.status(404).json({ error: 'File not found.' });
1508 }
1509
1510 const session = await createVideoStreamSession(filePath);
1511 res.json({
1512 sessionId: session.sessionId,
1513 playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
1514 durationSeconds: session.durationSeconds || null,
1515 videoWidth: session.videoWidth || null,
1516 videoHeight: session.videoHeight || null,
1517 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, imageBased: 0, skipped: 0 },
1518 subtitleTracks: session.subtitleTracks.map((track) => ({
1519 label: track.label,
1520 language: track.language,
1521 default: !!track.isDefault,
1522 src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`,
1523 })),
1524 imageSubtitleTracks: (session.imageSubtitleTracks || []).map((track) => ({
1525 label: track.label,
1526 language: track.language,
1527 default: !!track.isDefault,
1528 streamIndex: track.streamIndex,
1529 })),
1530 });
1531 } catch (err)
1532 {
1533 next(err);
1534 }
1535});
1536
1537// ---------------------------------------------------------------------------
1538// GET /api/files/video-stream/:sessionId/:assetPath(*)
1539// Streams HLS assets for a previously created short-lived video session.
1540// ---------------------------------------------------------------------------
1541router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>
1542{
1543 try
1544 {
1545 await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res);
1546 } catch (err)
1547 {
1548 next(err);
1549 }
1550});
1551
1552// ---------------------------------------------------------------------------
1553// DELETE /api/files/video-stream/:sessionId
1554// Authenticated. Explicitly releases an active short-lived video session.
1555// ---------------------------------------------------------------------------
1556router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>
1557{
1558 const sessionId = String(req.params.sessionId || '').trim();
1559 if (!sessionId) return res.status(400).json({ error: 'sessionId is required.' });
1560
1561 releaseVideoStreamSession(sessionId);
1562 res.json({ ok: true });
1563});
1564
1565// ---------------------------------------------------------------------------
1566// GET /api/files/video-stream-subtitle-frame
1567// Authenticated. Returns a rendered PNG subtitle bitmap at a given timestamp.
1568// Query params: filePath, streamIndex, timeSeconds
1569// ---------------------------------------------------------------------------
1570router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =>
1571{
1572 const requestReceivedAtMs = Date.now();
1573 try
1574 {
1575 const filePath = String(req.query.filePath || '').trim();
1576 const streamIndex = Number.parseInt(String(req.query.streamIndex || ''), 10);
1577 const timeSeconds = Number.parseFloat(String(req.query.timeSeconds || ''), 10);
1578 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
1579 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
1580
1581 if (!filePath || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(timeSeconds) || timeSeconds < 0)
1582 {
1583 return res.status(400).json({ error: 'filePath, streamIndex (non-negative int), and timeSeconds (non-negative number) are required.' });
1584 }
1585
1586 const { config, roots } = loadConfigAndRoots();
1587 const info = resolveRootForUser(filePath, roots, req.user, config);
1588 if (!info || !canReadInfo(req.user, info))
1589 {
1590 return res.status(403).json({ error: 'Access denied.' });
1591 }
1592
1593 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1594 {
1595 return res.status(404).json({ error: 'File not found.' });
1596 }
1597
1598 const canvasWidth = Number.isInteger(videoWidth) && videoWidth > 0 ? videoWidth : 1280;
1599 const canvasHeight = Number.isInteger(videoHeight) && videoHeight > 0 ? videoHeight : 720;
1600 const frameData = await renderImageSubtitleFrame({
1601 filePath,
1602 streamIndex,
1603 timeSeconds,
1604 canvasWidth,
1605 canvasHeight,
1606 });
1607
1608 if (!frameData || !frameData.frame)
1609 {
1610 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1611 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1612 res.set('X-Subtitle-Frame-Status', 'none');
1613 return res.status(204).end();
1614 }
1615
1616 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1617 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1618 res.set('X-Subtitle-Frame-Status', 'ok');
1619 res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));
1620 res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));
1621 res.set('X-Subtitle-Frame-Width', String(frameData.width || 0));
1622 res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));
1623 res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));
1624 res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));
1625 res.set('X-Subtitle-Frame-Start-Time', String(frameData.startTimeSeconds || 0));
1626 res.set('X-Subtitle-Frame-End-Time', String(frameData.endTimeSeconds || 0));
1627 res.set('Content-Type', 'image/png');
1628 res.set('Cache-Control', 'private, max-age=3600');
1629 res.send(frameData.frame);
1630 } catch (err)
1631 {
1632 logError('Subtitle frame extraction failed', err, {
1633 filePath: String(req.query.filePath || ''),
1634 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
1635 timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
1636 });
1637 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1638 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1639 res.set('X-Subtitle-Frame-Status', 'error');
1640 return res.status(204).end();
1641 }
1642});
1643
1644// ---------------------------------------------------------------------------
1645// GET /api/files/video-stream-subtitle-range
1646// Authenticated. Returns rendered PNG subtitle bitmaps overlapping a time range.
1647// Query params: filePath, streamIndex, startTimeSeconds, endTimeSeconds
1648// ---------------------------------------------------------------------------
1649router.get('/video-stream-subtitle-range', requireAuth, async (req, res) =>
1650{
1651 const requestReceivedAtMs = Date.now();
1652 try
1653 {
1654 const filePath = String(req.query.filePath || '').trim();
1655 const streamIndex = Number.parseInt(String(req.query.streamIndex || ''), 10);
1656 const startTimeSeconds = Number.parseFloat(String(req.query.startTimeSeconds || ''), 10);
1657 const endTimeSeconds = Number.parseFloat(String(req.query.endTimeSeconds || ''), 10);
1658 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
1659 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
1660
1661 if (!filePath || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds < startTimeSeconds)
1662 {
1663 return res.status(400).json({ error: 'filePath, streamIndex, startTimeSeconds, and endTimeSeconds are required.' });
1664 }
1665
1666 const { config, roots } = loadConfigAndRoots();
1667 const info = resolveRootForUser(filePath, roots, req.user, config);
1668 if (!info || !canReadInfo(req.user, info))
1669 {
1670 return res.status(403).json({ error: 'Access denied.' });
1671 }
1672
1673 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1674 {
1675 return res.status(404).json({ error: 'File not found.' });
1676 }
1677
1678 const canvasWidth = Number.isInteger(videoWidth) && videoWidth > 0 ? videoWidth : 1280;
1679 const canvasHeight = Number.isInteger(videoHeight) && videoHeight > 0 ? videoHeight : 720;
1680 const result = await renderImageSubtitleFramesInRange({
1681 filePath,
1682 streamIndex,
1683 startTimeSeconds,
1684 endTimeSeconds,
1685 canvasWidth,
1686 canvasHeight,
1687 });
1688
1689 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1690 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1691 res.json({
1692 status: 'ok',
1693 startTimeSeconds,
1694 endTimeSeconds,
1695 frames: Array.isArray(result && result.frames)
1696 ? result.frames.map((frame) => ({
1697 left: frame.left || 0,
1698 top: frame.top || 0,
1699 width: frame.width || 0,
1700 height: frame.height || 0,
1701 canvasWidth: frame.canvasWidth || canvasWidth,
1702 canvasHeight: frame.canvasHeight || canvasHeight,
1703 startTimeSeconds: frame.startTimeSeconds || 0,
1704 endTimeSeconds: frame.endTimeSeconds || 0,
1705 contentType: 'image/png',
1706 frameBase64: Buffer.from(frame.frame || Buffer.alloc(0)).toString('base64'),
1707 }))
1708 : [],
1709 });
1710 } catch (err)
1711 {
1712 logError('Subtitle range extraction failed', err, {
1713 filePath: String(req.query.filePath || ''),
1714 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
1715 startTimeSeconds: Number.parseFloat(String(req.query.startTimeSeconds || ''), 10),
1716 endTimeSeconds: Number.parseFloat(String(req.query.endTimeSeconds || ''), 10),
1717 });
1718 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1719 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1720 return res.status(200).json({ status: 'error', frames: [] });
1721 }
1722});
1723
1724// ---------------------------------------------------------------------------
1725// POST /api/files/video-stream-subtitle-log
1726// Authenticated. Persists client-side subtitle timing diagnostics to local cache.
1727// Body: { filePath, sessionId?, entries[] }
1728// ---------------------------------------------------------------------------
1729router.post('/video-stream-subtitle-log', requireAuth, (req, res) =>
1730{
1731 try
1732 {
1733 const filePath = String(req.body && req.body.filePath || '').trim();
1734 const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null;
1735 const sessionId = String(req.body && req.body.sessionId || '').trim();
1736
1737 if (!filePath || !entries || !entries.length)
1738 {
1739 return res.status(400).json({ error: 'filePath and entries are required.' });
1740 }
1741
1742 const { config, roots } = loadConfigAndRoots();
1743 const info = resolveRootForUser(filePath, roots, req.user, config);
1744 if (!info || !canReadInfo(req.user, info))
1745 {
1746 return res.status(403).json({ error: 'Access denied.' });
1747 }
1748
1749 appendSubtitleDebugEntries({
1750 videoName: path.basename(filePath),
1751 entries,
1752 context: {
1753 source: 'app',
1754 filePath,
1755 sessionId: sessionId || null,
1756 username: String(req.user && req.user.username || '').trim() || null,
1757 },
1758 });
1759
1760 return res.json({ ok: true });
1761 } catch (err)
1762 {
1763 logError('Subtitle debug log write failed', err, {
1764 filePath: String(req.body && req.body.filePath || ''),
1765 entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0,
1766 });
1767 return res.status(500).json({ error: 'Subtitle debug log write failed.' });
1768 }
1769});
1770
1771// ---------------------------------------------------------------------------
1772// GET /api/files/download-zip?dir=<absolute-path>
1773// Authenticated. Streams a zip of the given directory.
1774// ---------------------------------------------------------------------------
1775router.get('/download-zip', requireAuth, async (req, res) =>
1776{
1777 const dir = req.query.dir;
1778 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1779
1780 const { config, roots } = loadConfigAndRoots();
1781 const info = resolveRootForUser(dir, roots, req.user, config);
1782 if (!info || !canReadInfo(req.user, info))
1783 {
1784 return res.status(403).json({ error: 'Access denied.' });
1785 }
1786
1787 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1788 {
1789 return res.status(404).json({ error: 'Directory not found.' });
1790 }
1791
1792 // Use a hash of the dir path as cache key so concurrent users share the cache.
1793 const cacheKey = crypto.createHash('sha256').update(dir).digest('hex');
1794 try
1795 {
1796 const zipPath = await buildZip(dir, cacheKey);
1797 const zipName = `${path.basename(dir)}.zip`;
1798 res.download(zipPath, zipName);
1799 } catch (err)
1800 {
1801 res.status(500).json({ error: 'Failed to create zip archive.' });
1802 }
1803});
1804
1805// ---------------------------------------------------------------------------
1806// GET /api/files/thumbnail?file=<absolute-path>
1807// Returns a pre-generated cached thumbnail if present.
1808// ---------------------------------------------------------------------------
1809router.get('/thumbnail', requireAuth, async (req, res) =>
1810{
1811 const file = req.query.file;
1812 if (!file) return res.status(400).json({ error: 'file is required.' });
1813
1814 const { config, roots } = loadConfigAndRoots();
1815 const info = resolveRootForUser(file, roots, req.user, config);
1816 if (!info || !canReadInfo(req.user, info))
1817 {
1818 return res.status(403).json({ error: 'Access denied.' });
1819 }
1820
1821 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1822 {
1823 return res.status(404).json({ error: 'File not found.' });
1824 }
1825
1826 const thumb = await getCachedThumbnailInfo(file);
1827 if (!thumb)
1828 {
1829 return res.status(404).json({ error: 'Thumbnail not ready.' });
1830 }
1831
1832 res.type(thumb.contentType);
1833 res.set('Cache-Control', `private, max-age=${THUMB_HTTP_MAX_AGE_SEC}`);
1834 res.sendFile(thumb.thumbPath);
1835});
1836
1837// ---------------------------------------------------------------------------
1838// POST /api/files/upload?dir=<absolute-path>
1839// Accepts multipart file upload.
1840// ---------------------------------------------------------------------------
1841router.post('/upload', requireAuth, (req, res, next) =>
1842{
1843 const dir = req.query.dir;
1844 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1845
1846 const { config, roots } = loadConfigAndRoots();
1847 const info = resolveRootForUser(dir, roots, req.user, config);
1848 if (!info || !canWriteInfo(req.user, info))
1849 {
1850 return res.status(403).json({ error: 'Access denied.' });
1851 }
1852
1853 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1854 {
1855 return res.status(404).json({ error: 'Directory not found.' });
1856 }
1857
1858 const announcedSize = Number(req.header('x-upload-size') || 0);
1859 if (Number.isFinite(announcedSize) && announcedSize > 0)
1860 {
1861 const freeBytes = getFreeBytes(info.root);
1862 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
1863 {
1864 return res.status(413).json({
1865 error: 'Upload too large for remaining free space on selected root.',
1866 freeBytes,
1867 requiredBytes: announcedSize,
1868 });
1869 }
1870 }
1871
1872 // Enforce per-user folder size limit when uploading to a user folder.
1873 if (info.isUserFolder)
1874 {
1875 const addBytes = announcedSize > 0 ? announcedSize : 0;
1876 const limitError = checkUserFolderSizeLimit(config, req.user.username, addBytes);
1877 if (limitError) return res.status(413).json({ error: limitError });
1878 }
1879
1880 req._uploadDir = dir;
1881
1882 upload.array('files')(req, res, async (err) =>
1883 {
1884 if (err) return res.status(500).json({ error: err.message });
1885
1886 const db = getDb();
1887 for (const f of (req.files || []))
1888 {
1889 const filePath = path.join(dir, f.originalname);
1890 const uploadedAt = new Date().toISOString();
1891
1892 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
1893 if (existing)
1894 {
1895 db.prepare('UPDATE file_meta SET uploader = ?, sha256 = NULL, uploaded_at = ? WHERE file_path = ?')
1896 .run([req.user.username, uploadedAt, filePath]);
1897 } else
1898 {
1899 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at, sha256) VALUES (?, ?, ?, ?, ?, ?)')
1900 .run([filePath, req.user.username, '[]', '{}', uploadedAt, null]);
1901 }
1902
1903 enqueueFileHash(filePath);
1904 }
1905 try
1906 {
1907 await reindexDirectoryTree(dir);
1908 } catch
1909 {
1910 // Non-fatal search index refresh.
1911 }
1912
1913 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
1914 });
1915});
1916
1917// ---------------------------------------------------------------------------
1918// POST /api/files/rename
1919// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
1920// ---------------------------------------------------------------------------
1921router.post('/rename', requireAuth, (req, res) =>
1922{
1923 const { from, to } = req.body;
1924 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
1925
1926 // Prevent path traversal in the new name
1927 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
1928 {
1929 return res.status(400).json({ error: 'Invalid name.' });
1930 }
1931
1932 const { config, roots } = loadConfigAndRoots();
1933 const info = resolveRootForUser(from, roots, req.user, config);
1934 if (!info || !canWriteInfo(req.user, info))
1935 {
1936 return res.status(403).json({ error: 'Access denied.' });
1937 }
1938
1939 const dest = path.join(path.dirname(from), to);
1940
1941 // Ensure dest is still inside the same accessible root or user folder.
1942 if (!isAccessiblePath(dest, roots, req.user, config))
1943 {
1944 return res.status(403).json({ error: 'Access denied.' });
1945 }
1946
1947 try
1948 {
1949 movePathWithFallback(from, dest);
1950 } catch (err)
1951 {
1952 return res.status(500).json({ error: err.message });
1953 }
1954
1955 rewriteMetaPaths(from, dest);
1956 rewriteIndexPaths(from, dest);
1957
1958 res.json({ ok: true });
1959});
1960
1961// ---------------------------------------------------------------------------
1962// POST /api/files/move
1963// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1964// ---------------------------------------------------------------------------
1965router.post('/move', requireAuth, (req, res) =>
1966{
1967 const { from, toDir } = req.body;
1968 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1969 const targetName = req.body && req.body.targetName != null
1970 ? String(req.body.targetName).trim()
1971 : '';
1972 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1973 if (!['error', 'overwrite', 'rename'].includes(conflict))
1974 {
1975 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1976 }
1977
1978 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1979 {
1980 return res.status(400).json({ error: 'Invalid targetName.' });
1981 }
1982
1983 const { config, roots } = loadConfigAndRoots();
1984 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1985 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1986 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1987 if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1988 {
1989 return res.status(403).json({ error: 'Access denied.' });
1990 }
1991
1992 let sourceStat;
1993 let destStat;
1994 try
1995 {
1996 sourceStat = fs.statSync(from);
1997 destStat = fs.statSync(toDir);
1998 } catch
1999 {
2000 return res.status(404).json({ error: 'Source or destination not found.' });
2001 }
2002
2003 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
2004
2005 const requestedName = targetName || path.basename(from);
2006 const requestedDest = path.join(toDir, requestedName);
2007 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
2008
2009 // Enforce per-user folder size limit when moving into a user folder.
2010 if (toInfo.isUserFolder)
2011 {
2012 const sourceSize = getRecursiveSize(from);
2013 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceSize);
2014 if (limitError) return res.status(413).json({ error: limitError });
2015 }
2016 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
2017 {
2018 return res.status(400).json({ error: 'Cannot move onto itself.' });
2019 }
2020 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
2021 {
2022 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
2023 }
2024
2025 let dest = requestedDest;
2026 let resolvedConflict = 'none';
2027
2028 if (fs.existsSync(requestedDest))
2029 {
2030 if (conflict === 'error')
2031 {
2032 return res.status(409).json({ error: 'Destination already exists.' });
2033 }
2034
2035 if (conflict === 'rename')
2036 {
2037 dest = pickNumberedPath(toDir, requestedName);
2038 resolvedConflict = 'rename';
2039 }
2040
2041 if (conflict === 'overwrite')
2042 {
2043 try
2044 {
2045 removePathRecursive(requestedDest);
2046 } catch (err)
2047 {
2048 return res.status(500).json({ error: err.message });
2049 }
2050 resolvedConflict = 'overwrite';
2051 }
2052 }
2053
2054 if (sameResolvedPath(from, dest))
2055 {
2056 return res.status(400).json({ error: 'Cannot move onto itself.' });
2057 }
2058
2059 try
2060 {
2061 movePathWithFallback(from, dest);
2062 } catch (err)
2063 {
2064 return res.status(500).json({ error: err.message });
2065 }
2066
2067 rewriteMetaPaths(from, dest);
2068 rewriteIndexPaths(from, dest);
2069 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
2070});
2071
2072// ---------------------------------------------------------------------------
2073// POST /api/files/mkdir
2074// Body: { dir: <absolute-path>, name: <folder-name> }
2075// ---------------------------------------------------------------------------
2076router.post('/mkdir', requireAuth, (req, res) =>
2077{
2078 const { dir, name } = req.body;
2079 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
2080
2081 if (path.basename(name) !== name)
2082 {
2083 return res.status(400).json({ error: 'Invalid folder name.' });
2084 }
2085
2086 const { config, roots } = loadConfigAndRoots();
2087 const info = resolveRootForUser(dir, roots, req.user, config);
2088 if (!info || !canWriteInfo(req.user, info))
2089 {
2090 return res.status(403).json({ error: 'Access denied.' });
2091 }
2092
2093 const newDir = path.join(dir, name);
2094 if (!isAccessiblePath(newDir, roots, req.user, config))
2095 {
2096 return res.status(403).json({ error: 'Access denied.' });
2097 }
2098
2099 try
2100 {
2101 fs.mkdirSync(newDir, { recursive: false });
2102 } catch (err)
2103 {
2104 return res.status(500).json({ error: err.message });
2105 }
2106
2107 res.json({ ok: true, path: newDir });
2108});
2109
2110// ---------------------------------------------------------------------------
2111// POST /api/files/delete
2112// Body: { path: <absolute-path> }
2113// ---------------------------------------------------------------------------
2114router.post('/delete', requireAuth, (req, res) =>
2115{
2116 const target = req.body.path;
2117 if (!target) return res.status(400).json({ error: 'path is required.' });
2118
2119 const { config, roots } = loadConfigAndRoots();
2120 const info = resolveRootForUser(target, roots, req.user, config);
2121 if (!info || !canWriteInfo(req.user, info))
2122 {
2123 return res.status(403).json({ error: 'Access denied.' });
2124 }
2125
2126 // Do not allow deleting a configured root itself
2127 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
2128 {
2129 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
2130 }
2131
2132 try
2133 {
2134 const stat = fs.statSync(target);
2135 if (stat.isDirectory())
2136 {
2137 fs.rmSync(target, { recursive: true, force: true });
2138 } else
2139 {
2140 fs.unlinkSync(target);
2141 }
2142 } catch (err)
2143 {
2144 return res.status(500).json({ error: err.message });
2145 }
2146
2147 // Clean up any DB meta entries under that path
2148 const db = getDb();
2149 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
2150 .run([target, target + path.sep + '%']);
2151
2152 deleteIndexUnder(target);
2153
2154 res.json({ ok: true });
2155});
2156
2157// ---------------------------------------------------------------------------
2158// GET /api/files/folder-images?dir=<absolute-path>
2159// Returns files inside dir (recursive) that already have a cached thumbnail.
2160// Only files with a ready cached thumbnail are included.
2161// ---------------------------------------------------------------------------
2162router.get('/folder-images', requireAuth, async (req, res) =>
2163{
2164 const dir = String(req.query.dir || '').trim();
2165 if (!dir) return res.status(400).json({ error: 'dir is required.' });
2166
2167 const { config, roots } = loadConfigAndRoots();
2168 const info = resolveRootForUser(dir, roots, req.user, config);
2169 if (!info || !canReadInfo(req.user, info))
2170 {
2171 return res.status(403).json({ error: 'Access denied.' });
2172 }
2173
2174 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
2175 {
2176 return res.status(404).json({ error: 'Directory not found.' });
2177 }
2178
2179 const files = await getFilesWithThumbnailsInDir(dir);
2180 // Filter out any that escaped to a different accessible root (safety check).
2181 const filtered = files.filter(({ filePath }) => isAccessiblePath(filePath, roots, req.user, config));
2182
2183 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
2184});
2185
2186// ---------------------------------------------------------------------------
2187// GET /api/files/folder-icon?dir=<absolute-path>
2188// Returns the current icon source file for a folder (explicit or auto-first).
2189// ---------------------------------------------------------------------------
2190router.get('/folder-icon', requireAuth, async (req, res) =>
2191{
2192 const dir = String(req.query.dir || '').trim();
2193 if (!dir) return res.status(400).json({ error: 'dir is required.' });
2194
2195 const { config, roots } = loadConfigAndRoots();
2196 const info = resolveRootForUser(dir, roots, req.user, config);
2197 if (!info || !canReadInfo(req.user, info))
2198 {
2199 return res.status(403).json({ error: 'Access denied.' });
2200 }
2201
2202 const sourceFile = await getFolderIconSourceFile(dir);
2203 if (!sourceFile) return res.json({ icon: null });
2204
2205 // Verify the source is still accessible within a configured root or user folder.
2206 if (!isAccessiblePath(sourceFile, roots, req.user, config)) return res.json({ icon: null });
2207
2208 res.json({ icon: { filePath: sourceFile } });
2209});
2210
2211// ---------------------------------------------------------------------------
2212// POST /api/files/folder-icon
2213// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
2214// Requires write access; the image must already have a cached thumbnail.
2215// ---------------------------------------------------------------------------
2216router.post('/folder-icon', requireAuth, async (req, res) =>
2217{
2218 const folderPath = String((req.body && req.body.folderPath) || '').trim();
2219 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
2220
2221 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
2222
2223 const { config, roots } = loadConfigAndRoots();
2224 const info = resolveRootForUser(folderPath, roots, req.user, config);
2225 if (!info || !canWriteInfo(req.user, info))
2226 {
2227 return res.status(403).json({ error: 'Access denied.' });
2228 }
2229
2230 let stat;
2231 try { stat = fs.statSync(folderPath); }
2232 catch { return res.status(404).json({ error: 'Folder not found.' }); }
2233 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
2234
2235 if (rawImage !== null)
2236 {
2237 // Verify the image is inside a readable root or user folder.
2238 if (!isAccessiblePath(rawImage, roots, req.user, config)) return res.status(403).json({ error: 'Image not accessible.' });
2239
2240 // Must already have a cached thumbnail — only thumbnailed images can be selected.
2241 const thumb = await getCachedThumbnailInfo(rawImage);
2242 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
2243 }
2244
2245 await setFolderIconAssignment(folderPath, rawImage);
2246 res.json({ ok: true });
2247});
2248
2249// ---------------------------------------------------------------------------
2250// GET /api/files/global-favicon-image
2251// Serves the configured global favicon thumbnail file (cache-backed).
2252// Public so <link rel="icon"> can fetch it without auth headers.
2253// ---------------------------------------------------------------------------
2254router.get('/global-favicon-image', async (req, res) =>
2255{
2256 const config = loadConfig();
2257 const filePath = config && typeof config.globalFaviconPath === 'string'
2258 ? config.globalFaviconPath.trim()
2259 : '';
2260 if (!filePath) return res.status(404).end();
2261
2262 const thumb = await getCachedThumbnailInfo(filePath);
2263 if (!thumb || !thumb.thumbPath) return res.status(404).end();
2264 if (!fs.existsSync(thumb.thumbPath)) return res.status(404).end();
2265
2266 res.type(thumb.contentType || 'image/webp');
2267 res.sendFile(thumb.thumbPath);
2268});
2269
2270// ---------------------------------------------------------------------------
2271// GET /api/files/global-favicon
2272// Returns the configured global favicon source file path, if any.
2273// ---------------------------------------------------------------------------
2274router.get('/global-favicon', requireAuth, async (req, res) =>
2275{
2276 const config = loadConfig();
2277 const filePath = config && typeof config.globalFaviconPath === 'string'
2278 ? config.globalFaviconPath.trim()
2279 : '';
2280 if (!filePath) return res.json({ favicon: null });
2281
2282 const thumb = await getCachedThumbnailInfo(filePath);
2283 if (!thumb) return res.json({ favicon: null });
2284
2285 res.json({ favicon: { filePath } });
2286});
2287
2288// ---------------------------------------------------------------------------
2289// POST /api/files/global-favicon
2290// Body: { imagePath } where imagePath may be null to clear.
2291// Admin-only route for setting the global favicon source image.
2292// ---------------------------------------------------------------------------
2293router.post('/global-favicon', requireAuth, async (req, res) =>
2294{
2295 if (!req.user || !req.user.isAdmin)
2296 {
2297 return res.status(403).json({ error: 'Admin access required.' });
2298 }
2299
2300 const rawImage = req.body && req.body.imagePath != null
2301 ? String(req.body.imagePath).trim()
2302 : null;
2303
2304 const config = loadConfig();
2305 const roots = getEffectivePaths(config.paths || []);
2306
2307 if (rawImage !== null)
2308 {
2309 const info = resolveRootForUser(rawImage, roots, req.user, config);
2310 if (!info || !canReadInfo(req.user, info))
2311 {
2312 return res.status(403).json({ error: 'Image not accessible.' });
2313 }
2314
2315 const thumb = await getCachedThumbnailInfo(rawImage);
2316 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
2317 }
2318
2319 config.globalFaviconPath = rawImage;
2320 saveConfig(config);
2321 res.json({ ok: true });
2322});
2323
2324// ---------------------------------------------------------------------------
2325// POST /api/files/copy
2326// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
2327// Copies a file (not a directory) to the destination folder.
2328// Supports conflict: 'error' (default) | 'overwrite' | 'rename'
2329// ---------------------------------------------------------------------------
2330router.post('/copy', requireAuth, async (req, res) =>
2331{
2332 const { from, toDir } = req.body;
2333 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
2334 const targetName = req.body && req.body.targetName != null
2335 ? String(req.body.targetName).trim()
2336 : '';
2337 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
2338 if (!['error', 'overwrite', 'rename'].includes(conflict))
2339 {
2340 return res.status(400).json({ error: 'Invalid conflict strategy.' });
2341 }
2342
2343 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
2344 {
2345 return res.status(400).json({ error: 'Invalid targetName.' });
2346 }
2347
2348 const { config, roots } = loadConfigAndRoots();
2349 const fromInfo = resolveRootForUser(from, roots, req.user, config);
2350 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
2351 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
2352 if (!canReadInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
2353 {
2354 return res.status(403).json({ error: 'Access denied.' });
2355 }
2356
2357 let sourceStat;
2358 try { sourceStat = fs.statSync(from); }
2359 catch { return res.status(404).json({ error: 'Source not found.' }); }
2360
2361 if (sourceStat.isDirectory())
2362 {
2363 return res.status(400).json({ error: 'Copying directories is not supported.' });
2364 }
2365
2366 if (!fs.existsSync(toDir) || !fs.statSync(toDir).isDirectory())
2367 {
2368 return res.status(404).json({ error: 'Destination directory not found.' });
2369 }
2370
2371 const requestedName = targetName || path.basename(from);
2372 const requestedDest = path.join(toDir, requestedName);
2373 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
2374
2375 // Enforce per-user folder size limit when copying into a user folder.
2376 if (toInfo.isUserFolder)
2377 {
2378 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceStat.size);
2379 if (limitError) return res.status(413).json({ error: limitError });
2380 }
2381
2382 let dest = requestedDest;
2383 let resolvedConflict = 'none';
2384
2385 if (fs.existsSync(requestedDest))
2386 {
2387 if (conflict === 'error')
2388 {
2389 return res.status(409).json({ error: 'Destination already exists.' });
2390 }
2391 if (conflict === 'rename')
2392 {
2393 dest = pickNumberedPath(toDir, requestedName);
2394 resolvedConflict = 'rename';
2395 }
2396 if (conflict === 'overwrite')
2397 {
2398 resolvedConflict = 'overwrite';
2399 }
2400 }
2401
2402 try
2403 {
2404 fs.copyFileSync(from, dest);
2405 } catch (err)
2406 {
2407 return res.status(500).json({ error: err.message });
2408 }
2409
2410 try
2411 {
2412 await reindexDirectoryTree(toDir);
2413 } catch
2414 {
2415 // Non-fatal search index refresh.
2416 }
2417
2418 enqueueFileHash(dest);
2419
2420 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
2421});
2422
2423module.exports = router;