BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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