BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

294f7ec7 History
files.js 71.5 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const path = require('path');
5const fs = require('fs');
6const crypto = require('crypto');
7const multer = require('multer');
8const router = express.Router();
9
10const { getDb } = require('../db');
11const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
12const { requireAuth } = require('../auth');
13const { getCachedThumbnailInfo, getFilesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
14const { logError } = require('../logger');
15const { renderImageSubtitleFrame } = require('../image-subtitles');
16const { appendSubtitleDebugEntries, SUBTITLE_DEBUG_LOG_DIR } = require('../subtitle-debug-log');
17const { buildZip } = require('./share');
18const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
19
20// ---------------------------------------------------------------------------
21// SHA-256 hashing helper
22// ---------------------------------------------------------------------------
23
24/**
25 * Computes the SHA-256 hex digest of the file at `filePath`.
26 * Streams the file so it works for large files without loading them into memory.
27 * @param {string} filePath
28 * @returns {Promise<string>} hex digest
29 */
30function computeFileSha256 (filePath)
31{
32 return new Promise((resolve, reject) =>
33 {
34 const hash = crypto.createHash('sha256');
35 const stream = fs.createReadStream(filePath);
36 stream.on('error', reject);
37 stream.on('data', (chunk) => hash.update(chunk));
38 stream.on('end', () => resolve(hash.digest('hex')));
39 });
40}
41
42// ---------------------------------------------------------------------------
43// Multer storage — files are staged into temporary files and only promoted
44// to their final names after the full stream arrives.
45// ---------------------------------------------------------------------------
46function makeTempUploadPath (dir, originalName)
47{
48 const safeName = path.basename(String(originalName || 'upload'));
49 const suffix = crypto.randomUUID();
50 return path.join(dir, `.${safeName}.upload-${suffix}.part`);
51}
52
53function unlinkIfExists (targetPath, cb)
54{
55 fs.unlink(targetPath, (err) =>
56 {
57 if (!err || err.code === 'ENOENT') return cb(null);
58 cb(err);
59 });
60}
61
62function promoteUploadedFile (tempPath, finalPath, cb)
63{
64 fs.rename(tempPath, finalPath, cb);
65}
66
67const storage = {
68 _handleFile (req, file, cb)
69 {
70 if (!req._uploadDir)
71 {
72 cb(new Error('Upload directory is not set.'));
73 return;
74 }
75
76 const finalName = path.basename(String(file.originalname || 'upload'));
77 const finalPath = path.join(req._uploadDir, finalName);
78 const tempPath = makeTempUploadPath(req._uploadDir, finalName);
79 const out = fs.createWriteStream(tempPath, { flags: 'wx' });
80
81 let settled = false;
82 let cleaned = false;
83
84 const detach = () =>
85 {
86 req.off('aborted', onAbort);
87 req.off('close', onClose);
88 file.stream.off('error', onStreamError);
89 out.off('error', onWriteError);
90 out.off('finish', onFinish);
91 };
92
93 const stopPiping = () =>
94 {
95 // Prevent late file stream chunks from writing into a destroyed stream.
96 file.stream.unpipe(out);
97 if (typeof file.stream.resume === 'function') file.stream.resume();
98 };
99
100 const cleanup = (done) =>
101 {
102 if (cleaned) return done(null);
103 cleaned = true;
104 unlinkIfExists(tempPath, done);
105 };
106
107 const fail = (err) =>
108 {
109 if (settled) return;
110 settled = true;
111 stopPiping();
112 detach();
113
114 const finishFailure = () =>
115 {
116 cleanup((cleanupErr) => cb(cleanupErr || err));
117 };
118
119 if (out.destroyed || out.writableEnded)
120 {
121 finishFailure();
122 return;
123 }
124
125 out.end(finishFailure);
126 };
127
128 const succeed = () =>
129 {
130 if (settled) return;
131 settled = true;
132 detach();
133 cb(null, {
134 destination: req._uploadDir,
135 filename: finalName,
136 originalname: file.originalname,
137 path: finalPath,
138 size: out.bytesWritten,
139 });
140 };
141
142 const onAbort = () => fail(new Error('Upload aborted.'));
143 const onClose = () =>
144 {
145 if (!req.complete) onAbort();
146 };
147 const onStreamError = (err) => fail(err);
148 const onWriteError = (err) => fail(err);
149 const onFinish = () =>
150 {
151 if (req.aborted || !req.complete)
152 {
153 fail(new Error('Upload aborted.'));
154 return;
155 }
156
157 promoteUploadedFile(tempPath, finalPath, (err) =>
158 {
159 if (err)
160 {
161 fail(err);
162 return;
163 }
164 succeed();
165 });
166 };
167
168 req.on('aborted', onAbort);
169 req.on('close', onClose);
170 file.stream.on('error', onStreamError);
171 out.on('error', onWriteError);
172 out.on('finish', onFinish);
173 file.stream.pipe(out);
174 },
175
176 _removeFile (req, file, cb)
177 {
178 unlinkIfExists(file.path, cb);
179 },
180};
181
182const upload = multer({
183 storage,
184 limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB
185});
186
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 if (user && user.isAdmin && pathInsideResolved(absPath, SUBTITLE_DEBUG_LOG_DIR))
563 {
564 return {
565 root: SUBTITLE_DEBUG_LOG_DIR,
566 label: 'Subtitle Logs',
567 isUserFolder: false,
568 isDebugLogFolder: true,
569 };
570 }
571
572 // Regular configured roots first.
573 const matched = getAllowedRoot(absPath, roots);
574 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
575
576 // Check user personal folder.
577 if (!user || !user.username) return null;
578 const userFolder = getUserFolderPath(config, user.username);
579 if (!userFolder) return null;
580
581 const resolved = path.resolve(absPath);
582 const resolvedFolder = path.resolve(userFolder);
583 if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep))
584 {
585 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
586 }
587
588 // Admins can access orphaned user folders (folders without a matching account).
589 if (user && user.isAdmin)
590 {
591 const userFolderRoot = getUserFolderRootPath(config);
592 if (!userFolderRoot) return null;
593
594 const relative = path.relative(userFolderRoot, resolved);
595 if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
596
597 const parts = relative.split(path.sep).filter(Boolean);
598 if (!parts.length) return null;
599
600 const folderName = parts[0];
601 const usernames = existingUsernamesLowerSet();
602 if (usernames.has(String(folderName).toLowerCase())) return null;
603
604 const orphanRoot = path.join(userFolderRoot, folderName);
605 return {
606 root: orphanRoot,
607 label: folderName,
608 isUserFolder: false,
609 isOrphanUserFolder: true,
610 };
611 }
612
613 return null;
614}
615
616/**
617 * Checks whether the user has READ access to the resolved root info object
618 * returned by resolveRootForUser.
619 */
620function canReadInfo (user, info)
621{
622 if (!info) return false;
623 if (info.isUserFolder) return true; // owner always has full access
624 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
625 if (info.isDebugLogFolder) return !!(user && user.isAdmin);
626 return canRead(user, info.label);
627}
628
629/**
630 * Checks whether the user has WRITE access to the resolved root info object.
631 */
632function canWriteInfo (user, info)
633{
634 if (!info) return false;
635 if (info.isUserFolder) return true;
636 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
637 if (info.isDebugLogFolder) return false;
638 return canWrite(user, info.label);
639}
640
641/**
642 * Returns the size limit (bytes) for the user's personal folder, or null = unlimited.
643 */
644function getUserFolderSizeLimit (config)
645{
646 const lim = Number(config.userFolderSizeLimit);
647 return Number.isFinite(lim) && lim > 0 ? lim : null;
648}
649
650/**
651 * Returns an error message if adding `addedBytes` to the user's folder would
652 * exceed the size limit, or null if within limits.
653 */
654function checkUserFolderSizeLimit (config, username, addedBytes)
655{
656 const limit = getUserFolderSizeLimit(config);
657 if (!limit) return null;
658 const userFolder = getUserFolderPath(config, username);
659 if (!userFolder) return null;
660 const currentSize = getRecursiveSize(userFolder);
661 if (currentSize + addedBytes > limit)
662 {
663 return `Your personal folder is full (limit ${formatBytesServer(limit)}, used ${formatBytesServer(currentSize)}).`;
664 }
665 return null;
666}
667
668function formatBytesServer (bytes)
669{
670 if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
671 if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
672 if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
673 return `${bytes} B`;
674}
675
676/**
677 * Given an absolute path and the effective-paths list, return
678 * { root, label } where label is the base-name of the root, or null.
679 */
680function resolveRoot (absPath, roots)
681{
682 const matchedRoot = getAllowedRoot(absPath, roots);
683 if (!matchedRoot) return null;
684 return { root: matchedRoot, label: path.basename(matchedRoot) };
685}
686
687function sameResolvedPath (a, b)
688{
689 return path.resolve(String(a || '')) === path.resolve(String(b || ''));
690}
691
692function pathInsideResolved (child, root)
693{
694 const relative = path.relative(path.resolve(root), path.resolve(child));
695 return relative === '' || (!!relative && !relative.startsWith('..') && !path.isAbsolute(relative));
696}
697
698function uploadedAtFromStat (stat)
699{
700 if (!stat || typeof stat !== 'object') return null;
701 const birthtimeMs = Number(stat.birthtimeMs);
702 const ctimeMs = Number(stat.ctimeMs);
703 const mtimeMs = Number(stat.mtimeMs);
704
705 const chosenMs = (Number.isFinite(birthtimeMs) && birthtimeMs > 0)
706 ? birthtimeMs
707 : (Number.isFinite(ctimeMs) && ctimeMs > 0)
708 ? ctimeMs
709 : (Number.isFinite(mtimeMs) && mtimeMs > 0)
710 ? mtimeMs
711 : null;
712
713 if (!Number.isFinite(chosenMs) || chosenMs <= 0) return null;
714 return new Date(chosenMs).toISOString();
715}
716
717function rewriteMetaPaths (fromPath, toPath)
718{
719 const db = getDb();
720 const columns = db.prepare('PRAGMA table_info(file_meta)').all()
721 .map((col) => String(col.name || ''))
722 .filter(Boolean);
723
724 if (!columns.includes('file_path')) return;
725
726 const quotedColumns = columns.map((col) => `"${col}"`).join(', ');
727 const rows = db.prepare(`SELECT ${quotedColumns} FROM file_meta WHERE file_path = ? OR file_path LIKE ?`)
728 .all([fromPath, fromPath + path.sep + '%']);
729
730 if (!rows.length) return;
731
732 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
733 const placeholders = columns.map(() => '?').join(', ');
734 const updateAssignments = columns
735 .filter((col) => col !== 'file_path')
736 .map((col) => `"${col}" = excluded."${col}"`)
737 .join(',\n ');
738 const upsert = db.prepare(`
739 INSERT INTO file_meta (${quotedColumns})
740 VALUES (${placeholders})
741 ON CONFLICT(file_path) DO UPDATE SET
742 ${updateAssignments}
743 `);
744
745 for (const row of rows)
746 {
747 const nextPath = row.file_path === fromPath
748 ? toPath
749 : toPath + row.file_path.slice(fromPath.length);
750 del.run([row.file_path]);
751 const movedRow = {
752 ...row,
753 file_path: nextPath,
754 };
755 upsert.run(columns.map((col) => movedRow[col]));
756 }
757}
758
759function parseJsonArray (raw)
760{
761 try
762 {
763 const value = JSON.parse(raw || '[]');
764 return Array.isArray(value) ? value : [];
765 } catch
766 {
767 return [];
768 }
769}
770
771function parseJsonObject (raw)
772{
773 try
774 {
775 const value = JSON.parse(raw || '{}');
776 if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
777 return value;
778 } catch
779 {
780 return {};
781 }
782}
783
784function watchStatusForProgress (progress)
785{
786 if (!Number.isFinite(progress) || progress < 0) return null;
787 if (progress >= 0.7) return 'fully';
788 if (progress >= 0.05) return 'partway';
789 return null;
790}
791
792function normalisedWatchedStatus (value)
793{
794 const status = String(value || '').toLowerCase();
795 return status === 'fully' || status === 'partway' ? status : null;
796}
797
798function splitNameExt (name)
799{
800 const dot = String(name || '').lastIndexOf('.');
801 if (dot <= 0) return { stem: String(name || ''), ext: '' };
802 return {
803 stem: String(name).slice(0, dot),
804 ext: String(name).slice(dot),
805 };
806}
807
808function pickNumberedPath (dir, requestedName)
809{
810 const parsed = splitNameExt(requestedName);
811 const stem = parsed.stem || 'file';
812 const ext = parsed.ext || '';
813 let index = 1;
814
815 while (index <= 10000)
816 {
817 const candidateName = `${stem} (${index})${ext}`;
818 const candidatePath = path.join(dir, candidateName);
819 if (!fs.existsSync(candidatePath)) return candidatePath;
820 index++;
821 }
822
823 throw new Error('Could not generate a free destination name.');
824}
825
826function removePathRecursive (targetPath)
827{
828 const stat = fs.lstatSync(targetPath);
829 if (stat.isDirectory())
830 {
831 fs.rmSync(targetPath, { recursive: true, force: true });
832 } else
833 {
834 fs.unlinkSync(targetPath);
835 }
836}
837
838function movePathWithFallback (from, dest)
839{
840 const stat = fs.lstatSync(from);
841 try
842 {
843 fs.renameSync(from, dest);
844 return 'rename';
845 } catch (err)
846 {
847 try
848 {
849 if (stat.isDirectory())
850 {
851 fs.cpSync(from, dest, { recursive: true, force: true, preserveTimestamps: true });
852 } else
853 {
854 fs.copyFileSync(from, dest);
855 }
856 fs.rmSync(from, { recursive: true, force: true });
857 return 'copy-delete';
858 } catch (fallbackErr)
859 {
860 throw fallbackErr || err;
861 }
862 }
863}
864
865// ---------------------------------------------------------------------------
866// GET /api/files/roots
867// Returns the effective configured paths the user can read.
868// Also injects the user's personal folder when userPath is configured.
869// ---------------------------------------------------------------------------
870router.get('/roots', requireAuth, (req, res) =>
871{
872 const config = loadConfig();
873 const roots = getEffectivePaths(config.paths || []);
874 const rootAliases = rootAliasesFromConfig(config);
875
876 const readable = roots
877 .filter(r => canRead(req.user, path.basename(r)))
878 .map(r =>
879 {
880 const originalName = path.basename(r);
881 const alias = String(rootAliases[path.resolve(r)] || '').trim();
882 return {
883 label: alias || originalName,
884 path: r,
885 originalName,
886 alias: alias || null,
887 };
888 });
889
890 // Inject the user's personal folder when a userPath is configured.
891 if (req.user && req.user.username)
892 {
893 const userFolder = getUserFolderPath(config, req.user.username);
894 if (userFolder)
895 {
896 try { fs.mkdirSync(userFolder, { recursive: true }); } catch { /* non-fatal */ }
897 readable.unshift({
898 label: 'My Folder',
899 path: userFolder,
900 originalName: req.user.username,
901 alias: 'My Folder',
902 isUserFolder: true,
903 });
904 }
905 }
906
907 res.json({ roots: readable });
908});
909
910// ---------------------------------------------------------------------------
911// GET /api/files/root-access?rootPath=<absolute-root-path>
912// Returns users that can access a configured root and their mode (R / R+W).
913// ---------------------------------------------------------------------------
914router.get('/root-access', requireAuth, (req, res) =>
915{
916 const rootPath = String(req.query.rootPath || '').trim();
917 if (!rootPath)
918 {
919 return res.status(400).json({ error: 'rootPath is required.' });
920 }
921
922 const config = loadConfig();
923 const roots = getEffectivePaths(config.paths || []);
924 const info = resolveRoot(rootPath, roots);
925 if (!info) return res.status(403).json({ error: 'Access denied.' });
926 if (!sameResolvedPath(rootPath, info.root))
927 {
928 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
929 }
930 if (!canRead(req.user, info.label))
931 {
932 return res.status(403).json({ error: 'Access denied.' });
933 }
934
935 const db = getDb();
936 const rows = db.prepare('SELECT username, is_admin, permissions FROM users').all();
937 const users = [];
938
939 for (const row of rows)
940 {
941 if (row.is_admin === 1)
942 {
943 users.push({ username: row.username, mode: 'R+W' });
944 continue;
945 }
946
947 let permissions = {};
948 try
949 {
950 permissions = JSON.parse(row.permissions || '{}');
951 } catch
952 {
953 permissions = {};
954 }
955
956 const perm = permissions[info.label];
957 if (!perm || typeof perm !== 'object') continue;
958 const canWriteRoot = !!perm.write;
959 const canReadRoot = !!perm.read || canWriteRoot;
960 if (!canReadRoot) continue;
961 users.push({ username: row.username, mode: canWriteRoot ? 'R+W' : 'R' });
962 }
963
964 users.sort((a, b) =>
965 {
966 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
967 const byMode = modeRank(a.mode) - modeRank(b.mode);
968 if (byMode !== 0) return byMode;
969 return String(a.username).localeCompare(String(b.username));
970 });
971
972 const rootAliases = rootAliasesFromConfig(config);
973 const alias = String(rootAliases[path.resolve(info.root)] || '').trim();
974 res.json({
975 root: {
976 path: info.root,
977 label: alias || info.label,
978 originalName: info.label,
979 alias: alias || null,
980 },
981 users,
982 });
983});
984
985// ---------------------------------------------------------------------------
986// POST /api/files/root-alias
987// Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
988// Sets a display-only alias for a configured root.
989// ---------------------------------------------------------------------------
990router.post('/root-alias', requireAuth, (req, res) =>
991{
992 const rootPath = String(req.body && req.body.rootPath || '').trim();
993 const alias = String(req.body && req.body.alias || '').trim();
994 if (!rootPath || !alias)
995 {
996 return res.status(400).json({ error: 'rootPath and alias are required.' });
997 }
998
999 const roots = effectivePaths();
1000 const info = resolveRoot(rootPath, roots);
1001 if (!info) return res.status(403).json({ error: 'Access denied.' });
1002 if (!sameResolvedPath(rootPath, info.root))
1003 {
1004 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
1005 }
1006 if (!canWrite(req.user, info.label))
1007 {
1008 return res.status(403).json({ error: 'Access denied.' });
1009 }
1010
1011 const config = loadConfig();
1012 const rootAliases = rootAliasesFromConfig(config);
1013 const key = path.resolve(info.root);
1014 if (alias === info.label)
1015 {
1016 delete rootAliases[key];
1017 } else
1018 {
1019 rootAliases[key] = alias;
1020 }
1021 config.rootAliases = rootAliases;
1022 saveConfig(config);
1023
1024 res.json({
1025 ok: true,
1026 root: {
1027 path: info.root,
1028 label: alias,
1029 originalName: info.label,
1030 alias,
1031 },
1032 });
1033});
1034
1035// ---------------------------------------------------------------------------
1036// GET /api/files/list?dir=<absolute-path>
1037// Lists files and folders in the given directory.
1038// ---------------------------------------------------------------------------
1039router.get('/list', requireAuth, (req, res) =>
1040{
1041 const dir = req.query.dir;
1042 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1043
1044 const { config, roots } = loadConfigAndRoots();
1045 const info = resolveRootForUser(dir, roots, req.user, config);
1046 if (!info || !canReadInfo(req.user, info)) return res.status(403).json({ error: 'Access denied.' });
1047
1048 let entries;
1049 try
1050 {
1051 entries = fs.readdirSync(dir, { withFileTypes: true });
1052 } catch
1053 {
1054 return res.status(404).json({ error: 'Directory not found.' });
1055 }
1056
1057 const items = entries.map(e =>
1058 {
1059 const fullPath = path.join(dir, e.name);
1060 let size = null;
1061 let mtime = null;
1062 let uploadedAt = null;
1063 try
1064 {
1065 const stat = fs.statSync(fullPath);
1066 size = stat.size;
1067 mtime = stat.mtime.toISOString();
1068
1069 const db = getDb();
1070 const existing = db.prepare('SELECT uploaded_at FROM file_meta WHERE file_path = ?').get([fullPath]);
1071 uploadedAt = String(existing && existing.uploaded_at || '').trim() || uploadedAtFromStat(stat);
1072
1073 if (uploadedAt)
1074 {
1075 db.prepare(`
1076 INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at)
1077 VALUES (?, ?, ?, ?, ?)
1078 ON CONFLICT(file_path) DO UPDATE SET
1079 uploaded_at = COALESCE(NULLIF(file_meta.uploaded_at, ''), excluded.uploaded_at)
1080 `).run([fullPath, '', '[]', '{}', uploadedAt]);
1081 }
1082 } catch { /* ignore */ }
1083
1084 return {
1085 name: e.name,
1086 isDir: e.isDirectory(),
1087 size,
1088 mtime,
1089 uploadedAt,
1090 path: fullPath,
1091 };
1092 });
1093
1094 res.json({ items });
1095});
1096
1097// ---------------------------------------------------------------------------
1098// GET /api/files/search?query=<text>&limit=<number>
1099// Fuzzy-searches all readable roots for files.
1100// ---------------------------------------------------------------------------
1101router.get('/search', requireAuth, (req, res) =>
1102{
1103 const query = String(req.query.query || '').trim();
1104 if (!query) return res.status(400).json({ error: 'query is required.' });
1105
1106 const { config, roots } = loadConfigAndRoots();
1107 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
1108 .filter((rootPath) =>
1109 {
1110 try
1111 {
1112 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
1113 } catch
1114 {
1115 return false;
1116 }
1117 });
1118
1119 const results = searchFilesInRoots(query, readableRoots, req.query.limit);
1120 res.json({
1121 query,
1122 results,
1123 });
1124});
1125
1126// ---------------------------------------------------------------------------
1127// GET /api/files/search-images?query=<text>&limit=<number>
1128// Fuzzy-searches readable roots for image files that have ready thumbnails.
1129// ---------------------------------------------------------------------------
1130router.get('/search-images', requireAuth, async (req, res) =>
1131{
1132 const query = String(req.query.query || '').trim();
1133 if (!query) return res.status(400).json({ error: 'query is required.' });
1134 if (query.length < 2) return res.status(400).json({ error: 'query must be at least 2 characters.' });
1135
1136 const { config, roots } = loadConfigAndRoots();
1137 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
1138 .filter((rootPath) =>
1139 {
1140 try
1141 {
1142 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
1143 } catch
1144 {
1145 return false;
1146 }
1147 });
1148
1149 const { results, scannedFiles, truncated } = await searchImagesWithThumbnailsInRoots(
1150 query,
1151 readableRoots,
1152 req.query.limit,
1153 );
1154
1155 res.json({
1156 query,
1157 results,
1158 scannedFiles,
1159 truncated,
1160 });
1161});
1162
1163// ---------------------------------------------------------------------------
1164// GET /api/files/meta?file=<absolute-path>
1165// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
1166// ---------------------------------------------------------------------------
1167router.get('/meta', requireAuth, async (req, res) =>
1168{
1169 const file = req.query.file;
1170 if (!file) return res.status(400).json({ error: 'file is required.' });
1171
1172 const { config, roots } = loadConfigAndRoots();
1173 const info = resolveRootForUser(file, roots, req.user, config);
1174 if (!info || !canReadInfo(req.user, info))
1175 {
1176 return res.status(403).json({ error: 'Access denied.' });
1177 }
1178
1179 let stat;
1180 try
1181 {
1182 stat = fs.statSync(file);
1183 } catch
1184 {
1185 return res.status(404).json({ error: 'File not found.' });
1186 }
1187
1188 const db = getDb();
1189 let meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
1190 let uploadedAt = meta ? String(meta.uploaded_at || '').trim() : '';
1191 if (!uploadedAt)
1192 {
1193 uploadedAt = uploadedAtFromStat(stat) || '';
1194 if (uploadedAt)
1195 {
1196 db.prepare(`
1197 INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at)
1198 VALUES (?, ?, ?, ?, ?)
1199 ON CONFLICT(file_path) DO UPDATE SET
1200 uploaded_at = COALESCE(NULLIF(file_meta.uploaded_at, ''), excluded.uploaded_at)
1201 `).run([file, '', '[]', '{}', uploadedAt]);
1202
1203 meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
1204 }
1205 }
1206
1207 // Lazily compute and persist the SHA-256 hash when it is absent.
1208 let sha256 = meta ? (meta.sha256 || null) : null;
1209 if (!sha256 && !stat.isDirectory())
1210 {
1211 try
1212 {
1213 sha256 = await computeFileSha256(file);
1214 if (meta)
1215 {
1216 db.prepare('UPDATE file_meta SET sha256 = ? WHERE file_path = ?').run([sha256, file]);
1217 } else
1218 {
1219 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at, sha256) VALUES (?, ?, ?, ?, ?, ?)')
1220 .run([file, '', '[]', '{}', uploadedAt || uploadedAtFromStat(stat), sha256]);
1221 meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
1222 }
1223 } catch
1224 {
1225 // Non-fatal — hash will be retried next time.
1226 }
1227 }
1228
1229 res.json({
1230 name: path.basename(file),
1231 size: stat.size,
1232 mtime: stat.mtime.toISOString(),
1233 uploadedAt: uploadedAt || null,
1234 uploader: meta ? meta.uploader : '',
1235 downloaders: meta ? parseJsonArray(meta.downloaders) : [],
1236 watchedBy: meta ? parseJsonObject(meta.watched_by) : {},
1237 sha256: sha256 || null,
1238 });
1239});
1240
1241// ---------------------------------------------------------------------------
1242// GET /api/files/duplicates?file=<absolute-path>
1243// Returns other files with the same SHA-256 hash that the user can access.
1244// ---------------------------------------------------------------------------
1245router.get('/duplicates', requireAuth, (req, res) =>
1246{
1247 const file = req.query.file;
1248 if (!file) return res.status(400).json({ error: 'file is required.' });
1249
1250 const { config, roots } = loadConfigAndRoots();
1251 const info = resolveRootForUser(file, roots, req.user, config);
1252 if (!info || !canReadInfo(req.user, info))
1253 {
1254 return res.status(403).json({ error: 'Access denied.' });
1255 }
1256
1257 const db = getDb();
1258 const row = db.prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([file]);
1259 const hash = row ? (row.sha256 || null) : null;
1260 if (!hash)
1261 {
1262 return res.json({ duplicates: [] });
1263 }
1264
1265 // All other files sharing the same hash.
1266 const candidates = db.prepare(
1267 'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',
1268 ).all([hash, file]);
1269
1270 const duplicates = [];
1271 for (const { file_path } of candidates)
1272 {
1273 // Only return files inside a root the user can access and that still exist on disk.
1274 const dupInfo = resolveRootForUser(file_path, roots, req.user, config);
1275 if (!dupInfo || !canReadInfo(req.user, dupInfo)) continue;
1276 if (!fs.existsSync(file_path)) continue;
1277
1278 const rel = path.relative(dupInfo.root, file_path);
1279 const relativePath = rel && rel !== '' ? rel : path.basename(file_path);
1280
1281 duplicates.push({
1282 path: file_path,
1283 name: path.basename(file_path),
1284 dir: path.dirname(file_path),
1285 rootPath: dupInfo.root,
1286 relativePath,
1287 });
1288 }
1289
1290 res.json({ duplicates });
1291});
1292
1293// ---------------------------------------------------------------------------
1294// GET /api/files/space?dir=<absolute-path>
1295// Returns recursive used bytes for dir and available bytes on its root fs.
1296// ---------------------------------------------------------------------------
1297router.get('/space', requireAuth, (req, res) =>
1298{
1299 const dir = req.query.dir;
1300 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1301
1302 const { config, roots } = loadConfigAndRoots();
1303 const info = resolveRootForUser(dir, roots, req.user, config);
1304 if (!info || !canReadInfo(req.user, info))
1305 {
1306 return res.status(403).json({ error: 'Access denied.' });
1307 }
1308
1309 if (!fs.existsSync(dir))
1310 {
1311 return res.status(404).json({ error: 'Path not found.' });
1312 }
1313
1314 const usedBytes = getRecursiveSize(dir);
1315 const freeBytes = getFreeBytes(info.root);
1316 const userLimitBytes = info.isUserFolder ? getUserFolderSizeLimit(config) : null;
1317 const userFreeBytes = userLimitBytes == null ? null : Math.max(0, userLimitBytes - usedBytes);
1318 res.json({
1319 usedBytes,
1320 freeBytes,
1321 userLimitBytes,
1322 userFreeBytes,
1323 rootPath: info.root,
1324 rootLabel: info.label,
1325 });
1326});
1327
1328// ---------------------------------------------------------------------------
1329// GET /api/files/download?file=<absolute-path>
1330// Streams the file to the client; records the download.
1331// ---------------------------------------------------------------------------
1332router.get('/download', requireAuth, (req, res) =>
1333{
1334 const file = req.query.file;
1335 if (!file) return res.status(400).json({ error: 'file is required.' });
1336
1337 const { config, roots } = loadConfigAndRoots();
1338 const info = resolveRootForUser(file, roots, req.user, config);
1339 if (!info || !canReadInfo(req.user, info))
1340 {
1341 return res.status(403).json({ error: 'Access denied.' });
1342 }
1343
1344 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1345 {
1346 return res.status(404).json({ error: 'File not found.' });
1347 }
1348
1349 // Record download
1350 const db = getDb();
1351 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
1352 const uploadedAt = (() =>
1353 {
1354 try { return uploadedAtFromStat(fs.statSync(file)); }
1355 catch { return null; }
1356 })();
1357 if (meta)
1358 {
1359 const downloaders = parseJsonArray(meta.downloaders);
1360 if (!downloaders.includes(req.user.username))
1361 {
1362 downloaders.push(req.user.username);
1363 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
1364 .run([JSON.stringify(downloaders), file]);
1365 }
1366 } else
1367 {
1368 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at) VALUES (?, ?, ?, ?, ?)')
1369 .run([file, '', JSON.stringify([req.user.username]), '{}', uploadedAt]);
1370 }
1371
1372 res.download(file, path.basename(file));
1373});
1374
1375// ---------------------------------------------------------------------------
1376// POST /api/files/watched-statuses
1377// Body: { filePaths: [<absolute-path>, ...] }
1378// Returns per-path watched status for the authenticated user.
1379// ---------------------------------------------------------------------------
1380router.post('/watched-statuses', requireAuth, (req, res) =>
1381{
1382 const rawPaths = req.body && Array.isArray(req.body.filePaths) ? req.body.filePaths : null;
1383 if (!rawPaths)
1384 {
1385 return res.status(400).json({ error: 'filePaths array is required.' });
1386 }
1387
1388 const paths = rawPaths
1389 .map((p) => String(p || '').trim())
1390 .filter(Boolean)
1391 .slice(0, 500);
1392
1393 const { config, roots } = loadConfigAndRoots();
1394 const db = getDb();
1395 const statuses = {};
1396 const selectMeta = db.prepare('SELECT watched_by FROM file_meta WHERE file_path = ?');
1397
1398 for (const filePath of paths)
1399 {
1400 const info = resolveRootForUser(filePath, roots, req.user, config);
1401 if (!info || !canReadInfo(req.user, info)) continue;
1402
1403 let stat;
1404 try
1405 {
1406 stat = fs.statSync(filePath);
1407 } catch
1408 {
1409 continue;
1410 }
1411 if (stat.isDirectory()) continue;
1412
1413 const row = selectMeta.get([filePath]);
1414 const watchedBy = parseJsonObject(row && row.watched_by);
1415 const status = normalisedWatchedStatus(watchedBy[req.user.username]);
1416 if (status) statuses[filePath] = status;
1417 }
1418
1419 res.json({ statuses });
1420});
1421
1422// ---------------------------------------------------------------------------
1423// POST /api/files/watch-progress
1424// Body: { filePath: <absolute-path>, progress: <0..1> }
1425// Records per-user video watch state for sidebar display.
1426// ---------------------------------------------------------------------------
1427router.post('/watch-progress', requireAuth, (req, res) =>
1428{
1429 const filePath = String(req.body && req.body.filePath || '').trim();
1430 const progress = Number(req.body && req.body.progress);
1431 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
1432
1433 const status = watchStatusForProgress(progress);
1434 if (!status)
1435 {
1436 return res.json({ ok: true, updated: false });
1437 }
1438
1439 const { config, roots } = loadConfigAndRoots();
1440 const info = resolveRootForUser(filePath, roots, req.user, config);
1441 if (!info || !canReadInfo(req.user, info))
1442 {
1443 return res.status(403).json({ error: 'Access denied.' });
1444 }
1445
1446 let fileStat;
1447 try
1448 {
1449 fileStat = fs.statSync(filePath);
1450 } catch
1451 {
1452 return res.status(404).json({ error: 'File not found.' });
1453 }
1454
1455 if (fileStat.isDirectory())
1456 {
1457 return res.status(404).json({ error: 'File not found.' });
1458 }
1459
1460 const db = getDb();
1461 const row = db.prepare('SELECT uploader, downloaders, watched_by FROM file_meta WHERE file_path = ?').get([filePath]);
1462 const watchedBy = parseJsonObject(row && row.watched_by);
1463 const prev = String(watchedBy[req.user.username] || '').toLowerCase();
1464 const next = prev === 'fully' ? 'fully' : status;
1465 if (prev === next)
1466 {
1467 return res.json({ ok: true, updated: false, status: next });
1468 }
1469
1470 watchedBy[req.user.username] = next;
1471 if (row)
1472 {
1473 db.prepare('UPDATE file_meta SET watched_by = ? WHERE file_path = ?')
1474 .run([JSON.stringify(watchedBy), filePath]);
1475 } else
1476 {
1477 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at) VALUES (?, ?, ?, ?, ?)')
1478 .run([filePath, '', '[]', JSON.stringify(watchedBy), uploadedAtFromStat(fileStat)]);
1479 }
1480
1481 res.json({ ok: true, updated: true, status: next });
1482});
1483
1484// ---------------------------------------------------------------------------
1485// POST /api/files/video-stream
1486// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
1487// ---------------------------------------------------------------------------
1488router.post('/video-stream', requireAuth, async (req, res, next) =>
1489{
1490 try
1491 {
1492 const filePath = String(req.body?.filePath || '').trim();
1493 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
1494
1495 const { config, roots } = loadConfigAndRoots();
1496 const info = resolveRootForUser(filePath, roots, req.user, config);
1497 if (!info || !canReadInfo(req.user, info))
1498 {
1499 return res.status(403).json({ error: 'Access denied.' });
1500 }
1501
1502 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1503 {
1504 return res.status(404).json({ error: 'File not found.' });
1505 }
1506
1507 const session = await createVideoStreamSession(filePath);
1508 res.json({
1509 sessionId: session.sessionId,
1510 playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
1511 durationSeconds: session.durationSeconds || null,
1512 videoWidth: session.videoWidth || null,
1513 videoHeight: session.videoHeight || null,
1514 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, imageBased: 0, skipped: 0 },
1515 subtitleTracks: session.subtitleTracks.map((track) => ({
1516 label: track.label,
1517 language: track.language,
1518 default: !!track.isDefault,
1519 src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`,
1520 })),
1521 imageSubtitleTracks: (session.imageSubtitleTracks || []).map((track) => ({
1522 label: track.label,
1523 language: track.language,
1524 default: !!track.isDefault,
1525 streamIndex: track.streamIndex,
1526 })),
1527 });
1528 } catch (err)
1529 {
1530 next(err);
1531 }
1532});
1533
1534// ---------------------------------------------------------------------------
1535// GET /api/files/video-stream/:sessionId/:assetPath(*)
1536// Streams HLS assets for a previously created short-lived video session.
1537// ---------------------------------------------------------------------------
1538router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>
1539{
1540 try
1541 {
1542 await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res);
1543 } catch (err)
1544 {
1545 next(err);
1546 }
1547});
1548
1549// ---------------------------------------------------------------------------
1550// DELETE /api/files/video-stream/:sessionId
1551// Authenticated. Explicitly releases an active short-lived video session.
1552// ---------------------------------------------------------------------------
1553router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>
1554{
1555 const sessionId = String(req.params.sessionId || '').trim();
1556 if (!sessionId) return res.status(400).json({ error: 'sessionId is required.' });
1557
1558 releaseVideoStreamSession(sessionId);
1559 res.json({ ok: true });
1560});
1561
1562// ---------------------------------------------------------------------------
1563// GET /api/files/video-stream-subtitle-frame
1564// Authenticated. Returns a rendered PNG subtitle bitmap at a given timestamp.
1565// Query params: filePath, streamIndex, timeSeconds
1566// ---------------------------------------------------------------------------
1567router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =>
1568{
1569 const requestReceivedAtMs = Date.now();
1570 try
1571 {
1572 const filePath = String(req.query.filePath || '').trim();
1573 const streamIndex = Number.parseInt(String(req.query.streamIndex || ''), 10);
1574 const timeSeconds = Number.parseFloat(String(req.query.timeSeconds || ''), 10);
1575 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
1576 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
1577
1578 if (!filePath || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(timeSeconds) || timeSeconds < 0)
1579 {
1580 return res.status(400).json({ error: 'filePath, streamIndex (non-negative int), and timeSeconds (non-negative number) are required.' });
1581 }
1582
1583 const { config, roots } = loadConfigAndRoots();
1584 const info = resolveRootForUser(filePath, roots, req.user, config);
1585 if (!info || !canReadInfo(req.user, info))
1586 {
1587 return res.status(403).json({ error: 'Access denied.' });
1588 }
1589
1590 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1591 {
1592 return res.status(404).json({ error: 'File not found.' });
1593 }
1594
1595 const canvasWidth = Number.isInteger(videoWidth) && videoWidth > 0 ? videoWidth : 1280;
1596 const canvasHeight = Number.isInteger(videoHeight) && videoHeight > 0 ? videoHeight : 720;
1597 const frameData = await renderImageSubtitleFrame({
1598 filePath,
1599 streamIndex,
1600 timeSeconds,
1601 canvasWidth,
1602 canvasHeight,
1603 });
1604
1605 if (!frameData || !frameData.frame)
1606 {
1607 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1608 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1609 res.set('X-Subtitle-Frame-Status', 'none');
1610 return res.status(204).end();
1611 }
1612
1613 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1614 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1615 res.set('X-Subtitle-Frame-Status', 'ok');
1616 res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));
1617 res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));
1618 res.set('X-Subtitle-Frame-Width', String(frameData.width || 0));
1619 res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));
1620 res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));
1621 res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));
1622 res.set('X-Subtitle-Frame-Start-Time', String(frameData.startTimeSeconds || 0));
1623 res.set('X-Subtitle-Frame-End-Time', String(frameData.endTimeSeconds || 0));
1624 res.set('Content-Type', 'image/png');
1625 res.set('Cache-Control', 'private, max-age=3600');
1626 res.send(frameData.frame);
1627 } catch (err)
1628 {
1629 logError('Subtitle frame extraction failed', err, {
1630 filePath: String(req.query.filePath || ''),
1631 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
1632 timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
1633 });
1634 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1635 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1636 res.set('X-Subtitle-Frame-Status', 'error');
1637 return res.status(204).end();
1638 }
1639});
1640
1641// ---------------------------------------------------------------------------
1642// POST /api/files/video-stream-subtitle-log
1643// Authenticated. Persists client-side subtitle timing diagnostics to local cache.
1644// Body: { filePath, sessionId?, entries[] }
1645// ---------------------------------------------------------------------------
1646router.post('/video-stream-subtitle-log', requireAuth, (req, res) =>
1647{
1648 try
1649 {
1650 const filePath = String(req.body && req.body.filePath || '').trim();
1651 const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null;
1652 const sessionId = String(req.body && req.body.sessionId || '').trim();
1653
1654 if (!filePath || !entries || !entries.length)
1655 {
1656 return res.status(400).json({ error: 'filePath and entries are required.' });
1657 }
1658
1659 const { config, roots } = loadConfigAndRoots();
1660 const info = resolveRootForUser(filePath, roots, req.user, config);
1661 if (!info || !canReadInfo(req.user, info))
1662 {
1663 return res.status(403).json({ error: 'Access denied.' });
1664 }
1665
1666 appendSubtitleDebugEntries({
1667 videoName: path.basename(filePath),
1668 entries,
1669 context: {
1670 source: 'app',
1671 filePath,
1672 sessionId: sessionId || null,
1673 username: String(req.user && req.user.username || '').trim() || null,
1674 },
1675 });
1676
1677 return res.json({ ok: true });
1678 } catch (err)
1679 {
1680 logError('Subtitle debug log write failed', err, {
1681 filePath: String(req.body && req.body.filePath || ''),
1682 entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0,
1683 });
1684 return res.status(500).json({ error: 'Subtitle debug log write failed.' });
1685 }
1686});
1687
1688// ---------------------------------------------------------------------------
1689// GET /api/files/download-zip?dir=<absolute-path>
1690// Authenticated. Streams a zip of the given directory.
1691// ---------------------------------------------------------------------------
1692router.get('/download-zip', requireAuth, async (req, res) =>
1693{
1694 const dir = req.query.dir;
1695 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1696
1697 const { config, roots } = loadConfigAndRoots();
1698 const info = resolveRootForUser(dir, roots, req.user, config);
1699 if (!info || !canReadInfo(req.user, info))
1700 {
1701 return res.status(403).json({ error: 'Access denied.' });
1702 }
1703
1704 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1705 {
1706 return res.status(404).json({ error: 'Directory not found.' });
1707 }
1708
1709 // Use a hash of the dir path as cache key so concurrent users share the cache.
1710 const cacheKey = crypto.createHash('sha256').update(dir).digest('hex');
1711 try
1712 {
1713 const zipPath = await buildZip(dir, cacheKey);
1714 const zipName = `${path.basename(dir)}.zip`;
1715 res.download(zipPath, zipName);
1716 } catch (err)
1717 {
1718 res.status(500).json({ error: 'Failed to create zip archive.' });
1719 }
1720});
1721
1722// ---------------------------------------------------------------------------
1723// GET /api/files/thumbnail?file=<absolute-path>
1724// Returns a pre-generated cached thumbnail if present.
1725// ---------------------------------------------------------------------------
1726router.get('/thumbnail', requireAuth, async (req, res) =>
1727{
1728 const file = req.query.file;
1729 if (!file) return res.status(400).json({ error: 'file is required.' });
1730
1731 const { config, roots } = loadConfigAndRoots();
1732 const info = resolveRootForUser(file, roots, req.user, config);
1733 if (!info || !canReadInfo(req.user, info))
1734 {
1735 return res.status(403).json({ error: 'Access denied.' });
1736 }
1737
1738 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1739 {
1740 return res.status(404).json({ error: 'File not found.' });
1741 }
1742
1743 const thumb = await getCachedThumbnailInfo(file);
1744 if (!thumb)
1745 {
1746 return res.status(404).json({ error: 'Thumbnail not ready.' });
1747 }
1748
1749 res.type(thumb.contentType);
1750 res.set('Cache-Control', 'private, max-age=10');
1751 res.sendFile(thumb.thumbPath);
1752});
1753
1754// ---------------------------------------------------------------------------
1755// POST /api/files/upload?dir=<absolute-path>
1756// Accepts multipart file upload.
1757// ---------------------------------------------------------------------------
1758router.post('/upload', requireAuth, (req, res, next) =>
1759{
1760 const dir = req.query.dir;
1761 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1762
1763 const { config, roots } = loadConfigAndRoots();
1764 const info = resolveRootForUser(dir, roots, req.user, config);
1765 if (!info || !canWriteInfo(req.user, info))
1766 {
1767 return res.status(403).json({ error: 'Access denied.' });
1768 }
1769
1770 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1771 {
1772 return res.status(404).json({ error: 'Directory not found.' });
1773 }
1774
1775 const announcedSize = Number(req.header('x-upload-size') || 0);
1776 if (Number.isFinite(announcedSize) && announcedSize > 0)
1777 {
1778 const freeBytes = getFreeBytes(info.root);
1779 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
1780 {
1781 return res.status(413).json({
1782 error: 'Upload too large for remaining free space on selected root.',
1783 freeBytes,
1784 requiredBytes: announcedSize,
1785 });
1786 }
1787 }
1788
1789 // Enforce per-user folder size limit when uploading to a user folder.
1790 if (info.isUserFolder)
1791 {
1792 const addBytes = announcedSize > 0 ? announcedSize : 0;
1793 const limitError = checkUserFolderSizeLimit(config, req.user.username, addBytes);
1794 if (limitError) return res.status(413).json({ error: limitError });
1795 }
1796
1797 req._uploadDir = dir;
1798
1799 upload.array('files')(req, res, async (err) =>
1800 {
1801 if (err) return res.status(500).json({ error: err.message });
1802
1803 const db = getDb();
1804 for (const f of (req.files || []))
1805 {
1806 const filePath = path.join(dir, f.originalname);
1807 const uploadedAt = new Date().toISOString();
1808
1809 let sha256 = null;
1810 try
1811 {
1812 sha256 = await computeFileSha256(filePath);
1813 } catch
1814 {
1815 // Non-fatal — hash can be computed lazily when the file is accessed.
1816 }
1817
1818 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
1819 if (existing)
1820 {
1821 db.prepare('UPDATE file_meta SET uploader = ?, sha256 = ?, uploaded_at = ? WHERE file_path = ?')
1822 .run([req.user.username, sha256, uploadedAt, filePath]);
1823 } else
1824 {
1825 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at, sha256) VALUES (?, ?, ?, ?, ?, ?)')
1826 .run([filePath, req.user.username, '[]', '{}', uploadedAt, sha256]);
1827 }
1828 }
1829 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
1830 });
1831});
1832
1833// ---------------------------------------------------------------------------
1834// POST /api/files/rename
1835// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
1836// ---------------------------------------------------------------------------
1837router.post('/rename', requireAuth, (req, res) =>
1838{
1839 const { from, to } = req.body;
1840 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
1841
1842 // Prevent path traversal in the new name
1843 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
1844 {
1845 return res.status(400).json({ error: 'Invalid name.' });
1846 }
1847
1848 const { config, roots } = loadConfigAndRoots();
1849 const info = resolveRootForUser(from, roots, req.user, config);
1850 if (!info || !canWriteInfo(req.user, info))
1851 {
1852 return res.status(403).json({ error: 'Access denied.' });
1853 }
1854
1855 const dest = path.join(path.dirname(from), to);
1856
1857 // Ensure dest is still inside the same accessible root or user folder.
1858 if (!isAccessiblePath(dest, roots, req.user, config))
1859 {
1860 return res.status(403).json({ error: 'Access denied.' });
1861 }
1862
1863 try
1864 {
1865 movePathWithFallback(from, dest);
1866 } catch (err)
1867 {
1868 return res.status(500).json({ error: err.message });
1869 }
1870
1871 rewriteMetaPaths(from, dest);
1872
1873 res.json({ ok: true });
1874});
1875
1876// ---------------------------------------------------------------------------
1877// POST /api/files/move
1878// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1879// ---------------------------------------------------------------------------
1880router.post('/move', requireAuth, (req, res) =>
1881{
1882 const { from, toDir } = req.body;
1883 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1884 const targetName = req.body && req.body.targetName != null
1885 ? String(req.body.targetName).trim()
1886 : '';
1887 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1888 if (!['error', 'overwrite', 'rename'].includes(conflict))
1889 {
1890 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1891 }
1892
1893 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1894 {
1895 return res.status(400).json({ error: 'Invalid targetName.' });
1896 }
1897
1898 const { config, roots } = loadConfigAndRoots();
1899 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1900 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1901 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1902 if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1903 {
1904 return res.status(403).json({ error: 'Access denied.' });
1905 }
1906
1907 let sourceStat;
1908 let destStat;
1909 try
1910 {
1911 sourceStat = fs.statSync(from);
1912 destStat = fs.statSync(toDir);
1913 } catch
1914 {
1915 return res.status(404).json({ error: 'Source or destination not found.' });
1916 }
1917
1918 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
1919
1920 const requestedName = targetName || path.basename(from);
1921 const requestedDest = path.join(toDir, requestedName);
1922 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1923
1924 // Enforce per-user folder size limit when moving into a user folder.
1925 if (toInfo.isUserFolder)
1926 {
1927 const sourceSize = getRecursiveSize(from);
1928 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceSize);
1929 if (limitError) return res.status(413).json({ error: limitError });
1930 }
1931 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
1932 {
1933 return res.status(400).json({ error: 'Cannot move onto itself.' });
1934 }
1935 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
1936 {
1937 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
1938 }
1939
1940 let dest = requestedDest;
1941 let resolvedConflict = 'none';
1942
1943 if (fs.existsSync(requestedDest))
1944 {
1945 if (conflict === 'error')
1946 {
1947 return res.status(409).json({ error: 'Destination already exists.' });
1948 }
1949
1950 if (conflict === 'rename')
1951 {
1952 dest = pickNumberedPath(toDir, requestedName);
1953 resolvedConflict = 'rename';
1954 }
1955
1956 if (conflict === 'overwrite')
1957 {
1958 try
1959 {
1960 removePathRecursive(requestedDest);
1961 } catch (err)
1962 {
1963 return res.status(500).json({ error: err.message });
1964 }
1965 resolvedConflict = 'overwrite';
1966 }
1967 }
1968
1969 if (sameResolvedPath(from, dest))
1970 {
1971 return res.status(400).json({ error: 'Cannot move onto itself.' });
1972 }
1973
1974 try
1975 {
1976 movePathWithFallback(from, dest);
1977 } catch (err)
1978 {
1979 return res.status(500).json({ error: err.message });
1980 }
1981
1982 rewriteMetaPaths(from, dest);
1983 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1984});
1985
1986// ---------------------------------------------------------------------------
1987// POST /api/files/mkdir
1988// Body: { dir: <absolute-path>, name: <folder-name> }
1989// ---------------------------------------------------------------------------
1990router.post('/mkdir', requireAuth, (req, res) =>
1991{
1992 const { dir, name } = req.body;
1993 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
1994
1995 if (path.basename(name) !== name)
1996 {
1997 return res.status(400).json({ error: 'Invalid folder name.' });
1998 }
1999
2000 const { config, roots } = loadConfigAndRoots();
2001 const info = resolveRootForUser(dir, roots, req.user, config);
2002 if (!info || !canWriteInfo(req.user, info))
2003 {
2004 return res.status(403).json({ error: 'Access denied.' });
2005 }
2006
2007 const newDir = path.join(dir, name);
2008 if (!isAccessiblePath(newDir, roots, req.user, config))
2009 {
2010 return res.status(403).json({ error: 'Access denied.' });
2011 }
2012
2013 try
2014 {
2015 fs.mkdirSync(newDir, { recursive: false });
2016 } catch (err)
2017 {
2018 return res.status(500).json({ error: err.message });
2019 }
2020
2021 res.json({ ok: true, path: newDir });
2022});
2023
2024// ---------------------------------------------------------------------------
2025// POST /api/files/delete
2026// Body: { path: <absolute-path> }
2027// ---------------------------------------------------------------------------
2028router.post('/delete', requireAuth, (req, res) =>
2029{
2030 const target = req.body.path;
2031 if (!target) return res.status(400).json({ error: 'path is required.' });
2032
2033 const { config, roots } = loadConfigAndRoots();
2034 const info = resolveRootForUser(target, roots, req.user, config);
2035 if (!info || !canWriteInfo(req.user, info))
2036 {
2037 return res.status(403).json({ error: 'Access denied.' });
2038 }
2039
2040 // Do not allow deleting a configured root itself
2041 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
2042 {
2043 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
2044 }
2045
2046 try
2047 {
2048 const stat = fs.statSync(target);
2049 if (stat.isDirectory())
2050 {
2051 fs.rmSync(target, { recursive: true, force: true });
2052 } else
2053 {
2054 fs.unlinkSync(target);
2055 }
2056 } catch (err)
2057 {
2058 return res.status(500).json({ error: err.message });
2059 }
2060
2061 // Clean up any DB meta entries under that path
2062 const db = getDb();
2063 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
2064 .run([target, target + path.sep + '%']);
2065
2066 res.json({ ok: true });
2067});
2068
2069// ---------------------------------------------------------------------------
2070// GET /api/files/folder-images?dir=<absolute-path>
2071// Returns files inside dir (recursive) that already have a cached thumbnail.
2072// Only files with a ready cached thumbnail are included.
2073// ---------------------------------------------------------------------------
2074router.get('/folder-images', requireAuth, async (req, res) =>
2075{
2076 const dir = String(req.query.dir || '').trim();
2077 if (!dir) return res.status(400).json({ error: 'dir is required.' });
2078
2079 const { config, roots } = loadConfigAndRoots();
2080 const info = resolveRootForUser(dir, roots, req.user, config);
2081 if (!info || !canReadInfo(req.user, info))
2082 {
2083 return res.status(403).json({ error: 'Access denied.' });
2084 }
2085
2086 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
2087 {
2088 return res.status(404).json({ error: 'Directory not found.' });
2089 }
2090
2091 const files = await getFilesWithThumbnailsInDir(dir);
2092 // Filter out any that escaped to a different accessible root (safety check).
2093 const filtered = files.filter(({ filePath }) => isAccessiblePath(filePath, roots, req.user, config));
2094
2095 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
2096});
2097
2098// ---------------------------------------------------------------------------
2099// GET /api/files/folder-icon?dir=<absolute-path>
2100// Returns the current icon source file for a folder (explicit or auto-first).
2101// ---------------------------------------------------------------------------
2102router.get('/folder-icon', requireAuth, async (req, res) =>
2103{
2104 const dir = String(req.query.dir || '').trim();
2105 if (!dir) return res.status(400).json({ error: 'dir is required.' });
2106
2107 const { config, roots } = loadConfigAndRoots();
2108 const info = resolveRootForUser(dir, roots, req.user, config);
2109 if (!info || !canReadInfo(req.user, info))
2110 {
2111 return res.status(403).json({ error: 'Access denied.' });
2112 }
2113
2114 const sourceFile = await getFolderIconSourceFile(dir);
2115 if (!sourceFile) return res.json({ icon: null });
2116
2117 // Verify the source is still accessible within a configured root or user folder.
2118 if (!isAccessiblePath(sourceFile, roots, req.user, config)) return res.json({ icon: null });
2119
2120 res.json({ icon: { filePath: sourceFile } });
2121});
2122
2123// ---------------------------------------------------------------------------
2124// POST /api/files/folder-icon
2125// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
2126// Requires write access; the image must already have a cached thumbnail.
2127// ---------------------------------------------------------------------------
2128router.post('/folder-icon', requireAuth, async (req, res) =>
2129{
2130 const folderPath = String((req.body && req.body.folderPath) || '').trim();
2131 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
2132
2133 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
2134
2135 const { config, roots } = loadConfigAndRoots();
2136 const info = resolveRootForUser(folderPath, roots, req.user, config);
2137 if (!info || !canWriteInfo(req.user, info))
2138 {
2139 return res.status(403).json({ error: 'Access denied.' });
2140 }
2141
2142 let stat;
2143 try { stat = fs.statSync(folderPath); }
2144 catch { return res.status(404).json({ error: 'Folder not found.' }); }
2145 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
2146
2147 if (rawImage !== null)
2148 {
2149 // Verify the image is inside a readable root or user folder.
2150 if (!isAccessiblePath(rawImage, roots, req.user, config)) return res.status(403).json({ error: 'Image not accessible.' });
2151
2152 // Must already have a cached thumbnail — only thumbnailed images can be selected.
2153 const thumb = await getCachedThumbnailInfo(rawImage);
2154 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
2155 }
2156
2157 await setFolderIconAssignment(folderPath, rawImage);
2158 res.json({ ok: true });
2159});
2160
2161// ---------------------------------------------------------------------------
2162// GET /api/files/global-favicon-image
2163// Serves the configured global favicon thumbnail file (cache-backed).
2164// Public so <link rel="icon"> can fetch it without auth headers.
2165// ---------------------------------------------------------------------------
2166router.get('/global-favicon-image', async (req, res) =>
2167{
2168 const config = loadConfig();
2169 const filePath = config && typeof config.globalFaviconPath === 'string'
2170 ? config.globalFaviconPath.trim()
2171 : '';
2172 if (!filePath) return res.status(404).end();
2173
2174 const thumb = await getCachedThumbnailInfo(filePath);
2175 if (!thumb || !thumb.thumbPath) return res.status(404).end();
2176 if (!fs.existsSync(thumb.thumbPath)) return res.status(404).end();
2177
2178 res.type(thumb.contentType || 'image/webp');
2179 res.sendFile(thumb.thumbPath);
2180});
2181
2182// ---------------------------------------------------------------------------
2183// GET /api/files/global-favicon
2184// Returns the configured global favicon source file path, if any.
2185// ---------------------------------------------------------------------------
2186router.get('/global-favicon', requireAuth, async (req, res) =>
2187{
2188 const config = loadConfig();
2189 const filePath = config && typeof config.globalFaviconPath === 'string'
2190 ? config.globalFaviconPath.trim()
2191 : '';
2192 if (!filePath) return res.json({ favicon: null });
2193
2194 const thumb = await getCachedThumbnailInfo(filePath);
2195 if (!thumb) return res.json({ favicon: null });
2196
2197 res.json({ favicon: { filePath } });
2198});
2199
2200// ---------------------------------------------------------------------------
2201// POST /api/files/global-favicon
2202// Body: { imagePath } where imagePath may be null to clear.
2203// Admin-only route for setting the global favicon source image.
2204// ---------------------------------------------------------------------------
2205router.post('/global-favicon', requireAuth, async (req, res) =>
2206{
2207 if (!req.user || !req.user.isAdmin)
2208 {
2209 return res.status(403).json({ error: 'Admin access required.' });
2210 }
2211
2212 const rawImage = req.body && req.body.imagePath != null
2213 ? String(req.body.imagePath).trim()
2214 : null;
2215
2216 const config = loadConfig();
2217 const roots = getEffectivePaths(config.paths || []);
2218
2219 if (rawImage !== null)
2220 {
2221 const info = resolveRootForUser(rawImage, roots, req.user, config);
2222 if (!info || !canReadInfo(req.user, info))
2223 {
2224 return res.status(403).json({ error: 'Image not accessible.' });
2225 }
2226
2227 const thumb = await getCachedThumbnailInfo(rawImage);
2228 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
2229 }
2230
2231 config.globalFaviconPath = rawImage;
2232 saveConfig(config);
2233 res.json({ ok: true });
2234});
2235
2236// ---------------------------------------------------------------------------
2237// POST /api/files/copy
2238// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
2239// Copies a file (not a directory) to the destination folder.
2240// Supports conflict: 'error' (default) | 'overwrite' | 'rename'
2241// ---------------------------------------------------------------------------
2242router.post('/copy', requireAuth, (req, res) =>
2243{
2244 const { from, toDir } = req.body;
2245 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
2246 const targetName = req.body && req.body.targetName != null
2247 ? String(req.body.targetName).trim()
2248 : '';
2249 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
2250 if (!['error', 'overwrite', 'rename'].includes(conflict))
2251 {
2252 return res.status(400).json({ error: 'Invalid conflict strategy.' });
2253 }
2254
2255 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
2256 {
2257 return res.status(400).json({ error: 'Invalid targetName.' });
2258 }
2259
2260 const { config, roots } = loadConfigAndRoots();
2261 const fromInfo = resolveRootForUser(from, roots, req.user, config);
2262 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
2263 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
2264 if (!canReadInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
2265 {
2266 return res.status(403).json({ error: 'Access denied.' });
2267 }
2268
2269 let sourceStat;
2270 try { sourceStat = fs.statSync(from); }
2271 catch { return res.status(404).json({ error: 'Source not found.' }); }
2272
2273 if (sourceStat.isDirectory())
2274 {
2275 return res.status(400).json({ error: 'Copying directories is not supported.' });
2276 }
2277
2278 if (!fs.existsSync(toDir) || !fs.statSync(toDir).isDirectory())
2279 {
2280 return res.status(404).json({ error: 'Destination directory not found.' });
2281 }
2282
2283 const requestedName = targetName || path.basename(from);
2284 const requestedDest = path.join(toDir, requestedName);
2285 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
2286
2287 // Enforce per-user folder size limit when copying into a user folder.
2288 if (toInfo.isUserFolder)
2289 {
2290 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceStat.size);
2291 if (limitError) return res.status(413).json({ error: limitError });
2292 }
2293
2294 let dest = requestedDest;
2295 let resolvedConflict = 'none';
2296
2297 if (fs.existsSync(requestedDest))
2298 {
2299 if (conflict === 'error')
2300 {
2301 return res.status(409).json({ error: 'Destination already exists.' });
2302 }
2303 if (conflict === 'rename')
2304 {
2305 dest = pickNumberedPath(toDir, requestedName);
2306 resolvedConflict = 'rename';
2307 }
2308 if (conflict === 'overwrite')
2309 {
2310 resolvedConflict = 'overwrite';
2311 }
2312 }
2313
2314 try
2315 {
2316 fs.copyFileSync(from, dest);
2317 } catch (err)
2318 {
2319 return res.status(500).json({ error: err.message });
2320 }
2321
2322 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
2323});
2324
2325module.exports = router;