BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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