BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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