BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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