BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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