BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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