BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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