BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

userdirs
timfa Tim Falken · pushed by timfa · 6 months ago
f803c52f History
files.js 48.8 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, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
14const { buildZip } = require('./share');
15const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
16
17// ---------------------------------------------------------------------------
18// SHA-256 hashing helper
19// ---------------------------------------------------------------------------
20
21/**
22 * Computes the SHA-256 hex digest of the file at `filePath`.
23 * Streams the file so it works for large files without loading them into memory.
24 * @param {string} filePath
25 * @returns {Promise<string>} hex digest
26 */
27function computeFileSha256 (filePath)
28{
29 return new Promise((resolve, reject) =>
30 {
31 const hash = crypto.createHash('sha256');
32 const stream = fs.createReadStream(filePath);
33 stream.on('error', reject);
34 stream.on('data', (chunk) => hash.update(chunk));
35 stream.on('end', () => resolve(hash.digest('hex')));
36 });
37}
38
39// ---------------------------------------------------------------------------
40// Multer storage — files are staged into temporary files and only promoted
41// to their final names after the full stream arrives.
42// ---------------------------------------------------------------------------
43function makeTempUploadPath (dir, originalName)
44{
45 const safeName = path.basename(String(originalName || 'upload'));
46 const suffix = crypto.randomUUID();
47 return path.join(dir, `.${safeName}.upload-${suffix}.part`);
48}
49
50function unlinkIfExists (targetPath, cb)
51{
52 fs.unlink(targetPath, (err) =>
53 {
54 if (!err || err.code === 'ENOENT') return cb(null);
55 cb(err);
56 });
57}
58
59function promoteUploadedFile (tempPath, finalPath, cb)
60{
61 fs.rename(tempPath, finalPath, cb);
62}
63
64const storage = {
65 _handleFile (req, file, cb)
66 {
67 if (!req._uploadDir)
68 {
69 cb(new Error('Upload directory is not set.'));
70 return;
71 }
72
73 const finalName = path.basename(String(file.originalname || 'upload'));
74 const finalPath = path.join(req._uploadDir, finalName);
75 const tempPath = makeTempUploadPath(req._uploadDir, finalName);
76 const out = fs.createWriteStream(tempPath, { flags: 'wx' });
77
78 let settled = false;
79 let cleaned = false;
80
81 const detach = () =>
82 {
83 req.off('aborted', onAbort);
84 req.off('close', onClose);
85 file.stream.off('error', onStreamError);
86 out.off('error', onWriteError);
87 out.off('finish', onFinish);
88 };
89
90 const stopPiping = () =>
91 {
92 // Prevent late file stream chunks from writing into a destroyed stream.
93 file.stream.unpipe(out);
94 if (typeof file.stream.resume === 'function') file.stream.resume();
95 };
96
97 const cleanup = (done) =>
98 {
99 if (cleaned) return done(null);
100 cleaned = true;
101 unlinkIfExists(tempPath, done);
102 };
103
104 const fail = (err) =>
105 {
106 if (settled) return;
107 settled = true;
108 stopPiping();
109 detach();
110
111 const finishFailure = () =>
112 {
113 cleanup((cleanupErr) => cb(cleanupErr || err));
114 };
115
116 if (out.destroyed || out.writableEnded)
117 {
118 finishFailure();
119 return;
120 }
121
122 out.end(finishFailure);
123 };
124
125 const succeed = () =>
126 {
127 if (settled) return;
128 settled = true;
129 detach();
130 cb(null, {
131 destination: req._uploadDir,
132 filename: finalName,
133 originalname: file.originalname,
134 path: finalPath,
135 size: out.bytesWritten,
136 });
137 };
138
139 const onAbort = () => fail(new Error('Upload aborted.'));
140 const onClose = () =>
141 {
142 if (!req.complete) onAbort();
143 };
144 const onStreamError = (err) => fail(err);
145 const onWriteError = (err) => fail(err);
146 const onFinish = () =>
147 {
148 if (req.aborted || !req.complete)
149 {
150 fail(new Error('Upload aborted.'));
151 return;
152 }
153
154 promoteUploadedFile(tempPath, finalPath, (err) =>
155 {
156 if (err)
157 {
158 fail(err);
159 return;
160 }
161 succeed();
162 });
163 };
164
165 req.on('aborted', onAbort);
166 req.on('close', onClose);
167 file.stream.on('error', onStreamError);
168 out.on('error', onWriteError);
169 out.on('finish', onFinish);
170 file.stream.pipe(out);
171 },
172
173 _removeFile (req, file, cb)
174 {
175 unlinkIfExists(file.path, cb);
176 },
177};
178
179const upload = multer({
180 storage,
181 limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB
182});
183
184// ---------------------------------------------------------------------------
185// Helpers
186// ---------------------------------------------------------------------------
187
188function effectivePaths ()
189{
190 return getEffectivePaths(loadConfig().paths || []);
191}
192
193/**
194 * Loads config and returns { config, roots } together so both are consistent
195 * and user-folder checks can be performed in route handlers.
196 */
197function loadConfigAndRoots ()
198{
199 const config = loadConfig();
200 return { config, roots: getEffectivePaths(config.paths || []) };
201}
202
203/**
204 * Returns true when absPath is accessible to the user (either via a
205 * configured root or their personal folder).
206 */
207function isAccessiblePath (absPath, roots, user, config)
208{
209 return resolveRootForUser(absPath, roots, user, config) !== null;
210}
211
212function rootAliasesFromConfig (config)
213{
214 if (!config || typeof config !== 'object') return {};
215 if (!config.rootAliases || typeof config.rootAliases !== 'object') return {};
216 return config.rootAliases;
217}
218
219function getFreeBytes (targetPath)
220{
221 if (typeof fs.statfsSync !== 'function') return null;
222 try
223 {
224 const stat = fs.statfsSync(targetPath);
225 if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null;
226 return stat.bavail * stat.bsize;
227 } catch
228 {
229 return null;
230 }
231}
232
233function getRecursiveSize (targetPath)
234{
235 try
236 {
237 const stat = fs.statSync(targetPath);
238 if (!stat.isDirectory()) return stat.size;
239 } catch
240 {
241 return 0;
242 }
243
244 let total = 0;
245 let entries = [];
246 try
247 {
248 entries = fs.readdirSync(targetPath, { withFileTypes: true });
249 } catch
250 {
251 return 0;
252 }
253
254 for (const entry of entries)
255 {
256 const child = path.join(targetPath, entry.name);
257 if (entry.isDirectory())
258 {
259 total += getRecursiveSize(child);
260 continue;
261 }
262 try
263 {
264 total += fs.statSync(child).size;
265 } catch
266 {
267 // Ignore files that disappear during traversal.
268 }
269 }
270
271 return total;
272}
273
274/**
275 * Verify that the user has read access to the given configured-path label.
276 * `pathLabel` is the base-name of the effective path (shown in the UI).
277 */
278function canRead (user, pathLabel)
279{
280 if (user.isAdmin) return true;
281 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
282}
283
284function canWrite (user, pathLabel)
285{
286 if (user.isAdmin) return true;
287 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
288}
289
290// ---------------------------------------------------------------------------
291// User folder helpers
292// ---------------------------------------------------------------------------
293
294/**
295 * Returns the absolute path of the user's personal folder, or null.
296 * e.g. /data/userfolders/<username>
297 */
298function getUserFolderPath (config, username)
299{
300 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
301 if (!base) return null;
302 return path.join(base, String(username));
303}
304
305/**
306 * Resolves a request path against both the configured roots AND the user's
307 * personal folder. Returns { root, label, isUserFolder } or null.
308 * - isUserFolder: true when the path is inside the user's personal folder.
309 */
310function resolveRootForUser (absPath, roots, user, config)
311{
312 // Regular configured roots first.
313 const matched = getAllowedRoot(absPath, roots);
314 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
315
316 // Check user personal folder.
317 if (!user || !user.username) return null;
318 const userFolder = getUserFolderPath(config, user.username);
319 if (!userFolder) return null;
320
321 const resolved = path.resolve(absPath);
322 const resolvedFolder = path.resolve(userFolder);
323 if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep))
324 {
325 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
326 }
327
328 return null;
329}
330
331/**
332 * Checks whether the user has READ access to the resolved root info object
333 * returned by resolveRootForUser.
334 */
335function canReadInfo (user, info)
336{
337 if (!info) return false;
338 if (info.isUserFolder) return true; // owner always has full access
339 return canRead(user, info.label);
340}
341
342/**
343 * Checks whether the user has WRITE access to the resolved root info object.
344 */
345function canWriteInfo (user, info)
346{
347 if (!info) return false;
348 if (info.isUserFolder) return true;
349 return canWrite(user, info.label);
350}
351
352/**
353 * Returns the size limit (bytes) for the user's personal folder, or null = unlimited.
354 */
355function getUserFolderSizeLimit (config)
356{
357 const lim = Number(config.userFolderSizeLimit);
358 return Number.isFinite(lim) && lim > 0 ? lim : null;
359}
360
361/**
362 * Returns an error message if adding `addedBytes` to the user's folder would
363 * exceed the size limit, or null if within limits.
364 */
365function checkUserFolderSizeLimit (config, username, addedBytes)
366{
367 const limit = getUserFolderSizeLimit(config);
368 if (!limit) return null;
369 const userFolder = getUserFolderPath(config, username);
370 if (!userFolder) return null;
371 const currentSize = getRecursiveSize(userFolder);
372 if (currentSize + addedBytes > limit)
373 {
374 return `Your personal folder is full (limit ${formatBytesServer(limit)}, used ${formatBytesServer(currentSize)}).`;
375 }
376 return null;
377}
378
379function formatBytesServer (bytes)
380{
381 if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
382 if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
383 if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
384 return `${bytes} B`;
385}
386
387/**
388 * Given an absolute path and the effective-paths list, return
389 * { root, label } where label is the base-name of the root, or null.
390 */
391function resolveRoot (absPath, roots)
392{
393 const matchedRoot = getAllowedRoot(absPath, roots);
394 if (!matchedRoot) return null;
395 return { root: matchedRoot, label: path.basename(matchedRoot) };
396}
397
398function sameResolvedPath (a, b)
399{
400 return path.resolve(String(a || '')) === path.resolve(String(b || ''));
401}
402
403function pathInsideResolved (child, root)
404{
405 const relative = path.relative(path.resolve(root), path.resolve(child));
406 return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
407}
408
409function rewriteMetaPaths (fromPath, toPath)
410{
411 const db = getDb();
412 const rows = db.prepare('SELECT file_path, uploader, downloaders, watched_by, sha256 FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
413 .all([fromPath, fromPath + path.sep + '%']);
414
415 if (!rows.length) return;
416
417 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
418 const upsert = db.prepare(`
419 INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, sha256)
420 VALUES (?, ?, ?, ?, ?)
421 ON CONFLICT(file_path) DO UPDATE SET
422 uploader = excluded.uploader,
423 downloaders = excluded.downloaders,
424 watched_by = excluded.watched_by,
425 sha256 = excluded.sha256
426 `);
427
428 for (const row of rows)
429 {
430 const nextPath = row.file_path === fromPath
431 ? toPath
432 : toPath + row.file_path.slice(fromPath.length);
433 del.run([row.file_path]);
434 upsert.run([nextPath, row.uploader, row.downloaders, row.watched_by || '{}', row.sha256 || null]);
435 }
436}
437
438function parseJsonArray (raw)
439{
440 try
441 {
442 const value = JSON.parse(raw || '[]');
443 return Array.isArray(value) ? value : [];
444 } catch
445 {
446 return [];
447 }
448}
449
450function parseJsonObject (raw)
451{
452 try
453 {
454 const value = JSON.parse(raw || '{}');
455 if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
456 return value;
457 } catch
458 {
459 return {};
460 }
461}
462
463function watchStatusForProgress (progress)
464{
465 if (!Number.isFinite(progress) || progress < 0) return null;
466 if (progress >= 0.7) return 'fully';
467 if (progress >= 0.05) return 'partway';
468 return null;
469}
470
471function splitNameExt (name)
472{
473 const dot = String(name || '').lastIndexOf('.');
474 if (dot <= 0) return { stem: String(name || ''), ext: '' };
475 return {
476 stem: String(name).slice(0, dot),
477 ext: String(name).slice(dot),
478 };
479}
480
481function pickNumberedPath (dir, requestedName)
482{
483 const parsed = splitNameExt(requestedName);
484 const stem = parsed.stem || 'file';
485 const ext = parsed.ext || '';
486 let index = 1;
487
488 while (index <= 10000)
489 {
490 const candidateName = `${stem} (${index})${ext}`;
491 const candidatePath = path.join(dir, candidateName);
492 if (!fs.existsSync(candidatePath)) return candidatePath;
493 index++;
494 }
495
496 throw new Error('Could not generate a free destination name.');
497}
498
499function removePathRecursive (targetPath)
500{
501 const stat = fs.lstatSync(targetPath);
502 if (stat.isDirectory())
503 {
504 fs.rmSync(targetPath, { recursive: true, force: true });
505 } else
506 {
507 fs.unlinkSync(targetPath);
508 }
509}
510
511// ---------------------------------------------------------------------------
512// GET /api/files/roots
513// Returns the effective configured paths the user can read.
514// Also injects the user's personal folder when userPath is configured.
515// ---------------------------------------------------------------------------
516router.get('/roots', requireAuth, (req, res) =>
517{
518 const config = loadConfig();
519 const roots = getEffectivePaths(config.paths || []);
520 const rootAliases = rootAliasesFromConfig(config);
521
522 const readable = roots
523 .filter(r => canRead(req.user, path.basename(r)))
524 .map(r =>
525 {
526 const originalName = path.basename(r);
527 const alias = String(rootAliases[path.resolve(r)] || '').trim();
528 return {
529 label: alias || originalName,
530 path: r,
531 originalName,
532 alias: alias || null,
533 };
534 });
535
536 // Inject the user's personal folder when a userPath is configured.
537 if (req.user && req.user.username)
538 {
539 const userFolder = getUserFolderPath(config, req.user.username);
540 if (userFolder)
541 {
542 try { fs.mkdirSync(userFolder, { recursive: true }); } catch { /* non-fatal */ }
543 readable.unshift({
544 label: 'My Folder',
545 path: userFolder,
546 originalName: req.user.username,
547 alias: 'My Folder',
548 isUserFolder: true,
549 });
550 }
551 }
552
553 res.json({ roots: readable });
554});
555
556// ---------------------------------------------------------------------------
557// GET /api/files/root-access?rootPath=<absolute-root-path>
558// Returns users that can access a configured root and their mode (R / R+W).
559// ---------------------------------------------------------------------------
560router.get('/root-access', requireAuth, (req, res) =>
561{
562 const rootPath = String(req.query.rootPath || '').trim();
563 if (!rootPath)
564 {
565 return res.status(400).json({ error: 'rootPath is required.' });
566 }
567
568 const config = loadConfig();
569 const roots = getEffectivePaths(config.paths || []);
570 const info = resolveRoot(rootPath, roots);
571 if (!info) return res.status(403).json({ error: 'Access denied.' });
572 if (!sameResolvedPath(rootPath, info.root))
573 {
574 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
575 }
576 if (!canRead(req.user, info.label))
577 {
578 return res.status(403).json({ error: 'Access denied.' });
579 }
580
581 const db = getDb();
582 const rows = db.prepare('SELECT username, is_admin, permissions FROM users').all();
583 const users = [];
584
585 for (const row of rows)
586 {
587 if (row.is_admin === 1)
588 {
589 users.push({ username: row.username, mode: 'R+W' });
590 continue;
591 }
592
593 let permissions = {};
594 try
595 {
596 permissions = JSON.parse(row.permissions || '{}');
597 } catch
598 {
599 permissions = {};
600 }
601
602 const perm = permissions[info.label];
603 if (!perm || typeof perm !== 'object') continue;
604 const canWriteRoot = !!perm.write;
605 const canReadRoot = !!perm.read || canWriteRoot;
606 if (!canReadRoot) continue;
607 users.push({ username: row.username, mode: canWriteRoot ? 'R+W' : 'R' });
608 }
609
610 users.sort((a, b) =>
611 {
612 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
613 const byMode = modeRank(a.mode) - modeRank(b.mode);
614 if (byMode !== 0) return byMode;
615 return String(a.username).localeCompare(String(b.username));
616 });
617
618 const rootAliases = rootAliasesFromConfig(config);
619 const alias = String(rootAliases[path.resolve(info.root)] || '').trim();
620 res.json({
621 root: {
622 path: info.root,
623 label: alias || info.label,
624 originalName: info.label,
625 alias: alias || null,
626 },
627 users,
628 });
629});
630
631// ---------------------------------------------------------------------------
632// POST /api/files/root-alias
633// Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
634// Sets a display-only alias for a configured root.
635// ---------------------------------------------------------------------------
636router.post('/root-alias', requireAuth, (req, res) =>
637{
638 const rootPath = String(req.body && req.body.rootPath || '').trim();
639 const alias = String(req.body && req.body.alias || '').trim();
640 if (!rootPath || !alias)
641 {
642 return res.status(400).json({ error: 'rootPath and alias are required.' });
643 }
644
645 const roots = effectivePaths();
646 const info = resolveRoot(rootPath, roots);
647 if (!info) return res.status(403).json({ error: 'Access denied.' });
648 if (!sameResolvedPath(rootPath, info.root))
649 {
650 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
651 }
652 if (!canWrite(req.user, info.label))
653 {
654 return res.status(403).json({ error: 'Access denied.' });
655 }
656
657 const config = loadConfig();
658 const rootAliases = rootAliasesFromConfig(config);
659 const key = path.resolve(info.root);
660 if (alias === info.label)
661 {
662 delete rootAliases[key];
663 } else
664 {
665 rootAliases[key] = alias;
666 }
667 config.rootAliases = rootAliases;
668 saveConfig(config);
669
670 res.json({
671 ok: true,
672 root: {
673 path: info.root,
674 label: alias,
675 originalName: info.label,
676 alias,
677 },
678 });
679});
680
681// ---------------------------------------------------------------------------
682// GET /api/files/list?dir=<absolute-path>
683// Lists files and folders in the given directory.
684// ---------------------------------------------------------------------------
685router.get('/list', requireAuth, (req, res) =>
686{
687 const dir = req.query.dir;
688 if (!dir) return res.status(400).json({ error: 'dir is required.' });
689
690 const { config, roots } = loadConfigAndRoots();
691 const info = resolveRootForUser(dir, roots, req.user, config);
692 if (!info || !canReadInfo(req.user, info)) return res.status(403).json({ error: 'Access denied.' });
693
694 let entries;
695 try
696 {
697 entries = fs.readdirSync(dir, { withFileTypes: true });
698 } catch
699 {
700 return res.status(404).json({ error: 'Directory not found.' });
701 }
702
703 const items = entries.map(e =>
704 {
705 const fullPath = path.join(dir, e.name);
706 let size = null;
707 let mtime = null;
708 try
709 {
710 const stat = fs.statSync(fullPath);
711 size = stat.size;
712 mtime = stat.mtime.toISOString();
713 } catch { /* ignore */ }
714
715 return {
716 name: e.name,
717 isDir: e.isDirectory(),
718 size,
719 mtime,
720 path: fullPath,
721 };
722 });
723
724 res.json({ items });
725});
726
727// ---------------------------------------------------------------------------
728// GET /api/files/meta?file=<absolute-path>
729// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
730// ---------------------------------------------------------------------------
731router.get('/meta', requireAuth, async (req, res) =>
732{
733 const file = req.query.file;
734 if (!file) return res.status(400).json({ error: 'file is required.' });
735
736 const { config, roots } = loadConfigAndRoots();
737 const info = resolveRootForUser(file, roots, req.user, config);
738 if (!info || !canReadInfo(req.user, info))
739 {
740 return res.status(403).json({ error: 'Access denied.' });
741 }
742
743 let stat;
744 try
745 {
746 stat = fs.statSync(file);
747 } catch
748 {
749 return res.status(404).json({ error: 'File not found.' });
750 }
751
752 const db = getDb();
753 let meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
754
755 // Lazily compute and persist the SHA-256 hash when it is absent.
756 let sha256 = meta ? (meta.sha256 || null) : null;
757 if (!sha256 && !stat.isDirectory())
758 {
759 try
760 {
761 sha256 = await computeFileSha256(file);
762 if (meta)
763 {
764 db.prepare('UPDATE file_meta SET sha256 = ? WHERE file_path = ?').run([sha256, file]);
765 } else
766 {
767 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
768 .run([file, '', '[]', sha256]);
769 meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
770 }
771 } catch
772 {
773 // Non-fatal — hash will be retried next time.
774 }
775 }
776
777 res.json({
778 name: path.basename(file),
779 size: stat.size,
780 mtime: stat.mtime.toISOString(),
781 uploader: meta ? meta.uploader : '',
782 downloaders: meta ? parseJsonArray(meta.downloaders) : [],
783 watchedBy: meta ? parseJsonObject(meta.watched_by) : {},
784 sha256: sha256 || null,
785 });
786});
787
788// ---------------------------------------------------------------------------
789// GET /api/files/duplicates?file=<absolute-path>
790// Returns other files with the same SHA-256 hash that the user can access.
791// ---------------------------------------------------------------------------
792router.get('/duplicates', requireAuth, (req, res) =>
793{
794 const file = req.query.file;
795 if (!file) return res.status(400).json({ error: 'file is required.' });
796
797 const { config, roots } = loadConfigAndRoots();
798 const info = resolveRootForUser(file, roots, req.user, config);
799 if (!info || !canReadInfo(req.user, info))
800 {
801 return res.status(403).json({ error: 'Access denied.' });
802 }
803
804 const db = getDb();
805 const row = db.prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([file]);
806 const hash = row ? (row.sha256 || null) : null;
807 if (!hash)
808 {
809 return res.json({ duplicates: [] });
810 }
811
812 // All other files sharing the same hash.
813 const candidates = db.prepare(
814 'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',
815 ).all([hash, file]);
816
817 const duplicates = [];
818 for (const { file_path } of candidates)
819 {
820 // Only return files inside a root the user can access and that still exist on disk.
821 const dupInfo = resolveRootForUser(file_path, roots, req.user, config);
822 if (!dupInfo || !canReadInfo(req.user, dupInfo)) continue;
823 if (!fs.existsSync(file_path)) continue;
824
825 const rel = path.relative(dupInfo.root, file_path);
826 const relativePath = rel && rel !== '' ? rel : path.basename(file_path);
827
828 duplicates.push({
829 path: file_path,
830 name: path.basename(file_path),
831 dir: path.dirname(file_path),
832 rootPath: dupInfo.root,
833 relativePath,
834 });
835 }
836
837 res.json({ duplicates });
838});
839
840// ---------------------------------------------------------------------------
841// GET /api/files/space?dir=<absolute-path>
842// Returns recursive used bytes for dir and available bytes on its root fs.
843// ---------------------------------------------------------------------------
844router.get('/space', requireAuth, (req, res) =>
845{
846 const dir = req.query.dir;
847 if (!dir) return res.status(400).json({ error: 'dir is required.' });
848
849 const { config, roots } = loadConfigAndRoots();
850 const info = resolveRootForUser(dir, roots, req.user, config);
851 if (!info || !canReadInfo(req.user, info))
852 {
853 return res.status(403).json({ error: 'Access denied.' });
854 }
855
856 if (!fs.existsSync(dir))
857 {
858 return res.status(404).json({ error: 'Path not found.' });
859 }
860
861 const usedBytes = getRecursiveSize(dir);
862 const freeBytes = getFreeBytes(info.root);
863 const userLimitBytes = info.isUserFolder ? getUserFolderSizeLimit(config) : null;
864 const userFreeBytes = userLimitBytes == null ? null : Math.max(0, userLimitBytes - usedBytes);
865 res.json({
866 usedBytes,
867 freeBytes,
868 userLimitBytes,
869 userFreeBytes,
870 rootPath: info.root,
871 rootLabel: info.label,
872 });
873});
874
875// ---------------------------------------------------------------------------
876// GET /api/files/download?file=<absolute-path>
877// Streams the file to the client; records the download.
878// ---------------------------------------------------------------------------
879router.get('/download', requireAuth, (req, res) =>
880{
881 const file = req.query.file;
882 if (!file) return res.status(400).json({ error: 'file is required.' });
883
884 const { config, roots } = loadConfigAndRoots();
885 const info = resolveRootForUser(file, roots, req.user, config);
886 if (!info || !canReadInfo(req.user, info))
887 {
888 return res.status(403).json({ error: 'Access denied.' });
889 }
890
891 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
892 {
893 return res.status(404).json({ error: 'File not found.' });
894 }
895
896 // Record download
897 const db = getDb();
898 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
899 if (meta)
900 {
901 const downloaders = parseJsonArray(meta.downloaders);
902 if (!downloaders.includes(req.user.username))
903 {
904 downloaders.push(req.user.username);
905 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
906 .run([JSON.stringify(downloaders), file]);
907 }
908 } else
909 {
910 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
911 .run([file, '', JSON.stringify([req.user.username]), '{}']);
912 }
913
914 res.download(file, path.basename(file));
915});
916
917// ---------------------------------------------------------------------------
918// POST /api/files/watch-progress
919// Body: { filePath: <absolute-path>, progress: <0..1> }
920// Records per-user video watch state for sidebar display.
921// ---------------------------------------------------------------------------
922router.post('/watch-progress', requireAuth, (req, res) =>
923{
924 const filePath = String(req.body && req.body.filePath || '').trim();
925 const progress = Number(req.body && req.body.progress);
926 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
927
928 const status = watchStatusForProgress(progress);
929 if (!status)
930 {
931 return res.json({ ok: true, updated: false });
932 }
933
934 const { config, roots } = loadConfigAndRoots();
935 const info = resolveRootForUser(filePath, roots, req.user, config);
936 if (!info || !canReadInfo(req.user, info))
937 {
938 return res.status(403).json({ error: 'Access denied.' });
939 }
940
941 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
942 {
943 return res.status(404).json({ error: 'File not found.' });
944 }
945
946 const db = getDb();
947 const row = db.prepare('SELECT uploader, downloaders, watched_by FROM file_meta WHERE file_path = ?').get([filePath]);
948 const watchedBy = parseJsonObject(row && row.watched_by);
949 const prev = String(watchedBy[req.user.username] || '').toLowerCase();
950 const next = prev === 'fully' ? 'fully' : status;
951 if (prev === next)
952 {
953 return res.json({ ok: true, updated: false, status: next });
954 }
955
956 watchedBy[req.user.username] = next;
957 if (row)
958 {
959 db.prepare('UPDATE file_meta SET watched_by = ? WHERE file_path = ?')
960 .run([JSON.stringify(watchedBy), filePath]);
961 } else
962 {
963 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
964 .run([filePath, '', '[]', JSON.stringify(watchedBy)]);
965 }
966
967 res.json({ ok: true, updated: true, status: next });
968});
969
970// ---------------------------------------------------------------------------
971// POST /api/files/video-stream
972// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
973// ---------------------------------------------------------------------------
974router.post('/video-stream', requireAuth, async (req, res, next) =>
975{
976 try
977 {
978 const filePath = String(req.body?.filePath || '').trim();
979 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
980
981 const { config, roots } = loadConfigAndRoots();
982 const info = resolveRootForUser(filePath, roots, req.user, config);
983 if (!info || !canReadInfo(req.user, info))
984 {
985 return res.status(403).json({ error: 'Access denied.' });
986 }
987
988 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
989 {
990 return res.status(404).json({ error: 'File not found.' });
991 }
992
993 const session = await createVideoStreamSession(filePath);
994 res.json({
995 sessionId: session.sessionId,
996 playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
997 durationSeconds: session.durationSeconds || null,
998 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
999 subtitleTracks: session.subtitleTracks.map((track) => ({
1000 label: track.label,
1001 language: track.language,
1002 default: !!track.isDefault,
1003 src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`,
1004 })),
1005 });
1006 } catch (err)
1007 {
1008 next(err);
1009 }
1010});
1011
1012// ---------------------------------------------------------------------------
1013// GET /api/files/video-stream/:sessionId/:assetPath(*)
1014// Streams HLS assets for a previously created short-lived video session.
1015// ---------------------------------------------------------------------------
1016router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>
1017{
1018 try
1019 {
1020 await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res);
1021 } catch (err)
1022 {
1023 next(err);
1024 }
1025});
1026
1027// ---------------------------------------------------------------------------
1028// DELETE /api/files/video-stream/:sessionId
1029// Authenticated. Explicitly releases an active short-lived video session.
1030// ---------------------------------------------------------------------------
1031router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>
1032{
1033 const sessionId = String(req.params.sessionId || '').trim();
1034 if (!sessionId) return res.status(400).json({ error: 'sessionId is required.' });
1035
1036 releaseVideoStreamSession(sessionId);
1037 res.json({ ok: true });
1038});
1039
1040// ---------------------------------------------------------------------------
1041// GET /api/files/download-zip?dir=<absolute-path>
1042// Authenticated. Streams a zip of the given directory.
1043// ---------------------------------------------------------------------------
1044router.get('/download-zip', requireAuth, async (req, res) =>
1045{
1046 const dir = req.query.dir;
1047 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1048
1049 const { config, roots } = loadConfigAndRoots();
1050 const info = resolveRootForUser(dir, roots, req.user, config);
1051 if (!info || !canReadInfo(req.user, info))
1052 {
1053 return res.status(403).json({ error: 'Access denied.' });
1054 }
1055
1056 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1057 {
1058 return res.status(404).json({ error: 'Directory not found.' });
1059 }
1060
1061 // Use a hash of the dir path as cache key so concurrent users share the cache.
1062 const cacheKey = crypto.createHash('sha256').update(dir).digest('hex');
1063 try
1064 {
1065 const zipPath = await buildZip(dir, cacheKey);
1066 const zipName = `${path.basename(dir)}.zip`;
1067 res.download(zipPath, zipName);
1068 } catch (err)
1069 {
1070 res.status(500).json({ error: 'Failed to create zip archive.' });
1071 }
1072});
1073
1074// ---------------------------------------------------------------------------
1075// GET /api/files/thumbnail?file=<absolute-path>
1076// Returns a pre-generated cached thumbnail if present.
1077// ---------------------------------------------------------------------------
1078router.get('/thumbnail', requireAuth, async (req, res) =>
1079{
1080 const file = req.query.file;
1081 if (!file) return res.status(400).json({ error: 'file is required.' });
1082
1083 const { config, roots } = loadConfigAndRoots();
1084 const info = resolveRootForUser(file, roots, req.user, config);
1085 if (!info || !canReadInfo(req.user, info))
1086 {
1087 return res.status(403).json({ error: 'Access denied.' });
1088 }
1089
1090 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1091 {
1092 return res.status(404).json({ error: 'File not found.' });
1093 }
1094
1095 const thumb = await getCachedThumbnailInfo(file);
1096 if (!thumb)
1097 {
1098 return res.status(404).json({ error: 'Thumbnail not ready.' });
1099 }
1100
1101 res.type(thumb.contentType);
1102 res.set('Cache-Control', 'private, max-age=10');
1103 res.sendFile(thumb.thumbPath);
1104});
1105
1106// ---------------------------------------------------------------------------
1107// POST /api/files/upload?dir=<absolute-path>
1108// Accepts multipart file upload.
1109// ---------------------------------------------------------------------------
1110router.post('/upload', requireAuth, (req, res, next) =>
1111{
1112 const dir = req.query.dir;
1113 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1114
1115 const { config, roots } = loadConfigAndRoots();
1116 const info = resolveRootForUser(dir, roots, req.user, config);
1117 if (!info || !canWriteInfo(req.user, info))
1118 {
1119 return res.status(403).json({ error: 'Access denied.' });
1120 }
1121
1122 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1123 {
1124 return res.status(404).json({ error: 'Directory not found.' });
1125 }
1126
1127 const announcedSize = Number(req.header('x-upload-size') || 0);
1128 if (Number.isFinite(announcedSize) && announcedSize > 0)
1129 {
1130 const freeBytes = getFreeBytes(info.root);
1131 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
1132 {
1133 return res.status(413).json({
1134 error: 'Upload too large for remaining free space on selected root.',
1135 freeBytes,
1136 requiredBytes: announcedSize,
1137 });
1138 }
1139 }
1140
1141 // Enforce per-user folder size limit when uploading to a user folder.
1142 if (info.isUserFolder)
1143 {
1144 const addBytes = announcedSize > 0 ? announcedSize : 0;
1145 const limitError = checkUserFolderSizeLimit(config, req.user.username, addBytes);
1146 if (limitError) return res.status(413).json({ error: limitError });
1147 }
1148
1149 req._uploadDir = dir;
1150
1151 upload.array('files')(req, res, async (err) =>
1152 {
1153 if (err) return res.status(500).json({ error: err.message });
1154
1155 const db = getDb();
1156 for (const f of (req.files || []))
1157 {
1158 const filePath = path.join(dir, f.originalname);
1159
1160 let sha256 = null;
1161 try
1162 {
1163 sha256 = await computeFileSha256(filePath);
1164 } catch
1165 {
1166 // Non-fatal — hash can be computed lazily when the file is accessed.
1167 }
1168
1169 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
1170 if (existing)
1171 {
1172 db.prepare('UPDATE file_meta SET uploader = ?, sha256 = ? WHERE file_path = ?')
1173 .run([req.user.username, sha256, filePath]);
1174 } else
1175 {
1176 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1177 .run([filePath, req.user.username, '[]', sha256]);
1178 }
1179 }
1180 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
1181 });
1182});
1183
1184// ---------------------------------------------------------------------------
1185// POST /api/files/rename
1186// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
1187// ---------------------------------------------------------------------------
1188router.post('/rename', requireAuth, (req, res) =>
1189{
1190 const { from, to } = req.body;
1191 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
1192
1193 // Prevent path traversal in the new name
1194 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
1195 {
1196 return res.status(400).json({ error: 'Invalid name.' });
1197 }
1198
1199 const { config, roots } = loadConfigAndRoots();
1200 const info = resolveRootForUser(from, roots, req.user, config);
1201 if (!info || !canWriteInfo(req.user, info))
1202 {
1203 return res.status(403).json({ error: 'Access denied.' });
1204 }
1205
1206 const dest = path.join(path.dirname(from), to);
1207
1208 // Ensure dest is still inside the same accessible root or user folder.
1209 if (!isAccessiblePath(dest, roots, req.user, config))
1210 {
1211 return res.status(403).json({ error: 'Access denied.' });
1212 }
1213
1214 try
1215 {
1216 fs.renameSync(from, dest);
1217 } catch (err)
1218 {
1219 return res.status(500).json({ error: err.message });
1220 }
1221
1222 rewriteMetaPaths(from, dest);
1223
1224 res.json({ ok: true });
1225});
1226
1227// ---------------------------------------------------------------------------
1228// POST /api/files/move
1229// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1230// ---------------------------------------------------------------------------
1231router.post('/move', requireAuth, (req, res) =>
1232{
1233 const { from, toDir } = req.body;
1234 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1235 const targetName = req.body && req.body.targetName != null
1236 ? String(req.body.targetName).trim()
1237 : '';
1238 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1239 if (!['error', 'overwrite', 'rename'].includes(conflict))
1240 {
1241 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1242 }
1243
1244 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1245 {
1246 return res.status(400).json({ error: 'Invalid targetName.' });
1247 }
1248
1249 const { config, roots } = loadConfigAndRoots();
1250 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1251 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1252 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1253 if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1254 {
1255 return res.status(403).json({ error: 'Access denied.' });
1256 }
1257
1258 let sourceStat;
1259 let destStat;
1260 try
1261 {
1262 sourceStat = fs.statSync(from);
1263 destStat = fs.statSync(toDir);
1264 } catch
1265 {
1266 return res.status(404).json({ error: 'Source or destination not found.' });
1267 }
1268
1269 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
1270
1271 const requestedName = targetName || path.basename(from);
1272 const requestedDest = path.join(toDir, requestedName);
1273 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1274
1275 // Enforce per-user folder size limit when moving into a user folder.
1276 if (toInfo.isUserFolder)
1277 {
1278 const sourceSize = getRecursiveSize(from);
1279 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceSize);
1280 if (limitError) return res.status(413).json({ error: limitError });
1281 }
1282 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
1283 {
1284 return res.status(400).json({ error: 'Cannot move onto itself.' });
1285 }
1286 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
1287 {
1288 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
1289 }
1290
1291 let dest = requestedDest;
1292 let resolvedConflict = 'none';
1293
1294 if (fs.existsSync(requestedDest))
1295 {
1296 if (conflict === 'error')
1297 {
1298 return res.status(409).json({ error: 'Destination already exists.' });
1299 }
1300
1301 if (conflict === 'rename')
1302 {
1303 dest = pickNumberedPath(toDir, requestedName);
1304 resolvedConflict = 'rename';
1305 }
1306
1307 if (conflict === 'overwrite')
1308 {
1309 try
1310 {
1311 removePathRecursive(requestedDest);
1312 } catch (err)
1313 {
1314 return res.status(500).json({ error: err.message });
1315 }
1316 resolvedConflict = 'overwrite';
1317 }
1318 }
1319
1320 if (sameResolvedPath(from, dest))
1321 {
1322 return res.status(400).json({ error: 'Cannot move onto itself.' });
1323 }
1324
1325 try
1326 {
1327 fs.renameSync(from, dest);
1328 } catch (err)
1329 {
1330 return res.status(500).json({ error: err.message });
1331 }
1332
1333 rewriteMetaPaths(from, dest);
1334 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1335});
1336
1337// ---------------------------------------------------------------------------
1338// POST /api/files/mkdir
1339// Body: { dir: <absolute-path>, name: <folder-name> }
1340// ---------------------------------------------------------------------------
1341router.post('/mkdir', requireAuth, (req, res) =>
1342{
1343 const { dir, name } = req.body;
1344 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
1345
1346 if (path.basename(name) !== name)
1347 {
1348 return res.status(400).json({ error: 'Invalid folder name.' });
1349 }
1350
1351 const { config, roots } = loadConfigAndRoots();
1352 const info = resolveRootForUser(dir, roots, req.user, config);
1353 if (!info || !canWriteInfo(req.user, info))
1354 {
1355 return res.status(403).json({ error: 'Access denied.' });
1356 }
1357
1358 const newDir = path.join(dir, name);
1359 if (!isAccessiblePath(newDir, roots, req.user, config))
1360 {
1361 return res.status(403).json({ error: 'Access denied.' });
1362 }
1363
1364 try
1365 {
1366 fs.mkdirSync(newDir, { recursive: false });
1367 } catch (err)
1368 {
1369 return res.status(500).json({ error: err.message });
1370 }
1371
1372 res.json({ ok: true, path: newDir });
1373});
1374
1375// ---------------------------------------------------------------------------
1376// POST /api/files/delete
1377// Body: { path: <absolute-path> }
1378// ---------------------------------------------------------------------------
1379router.post('/delete', requireAuth, (req, res) =>
1380{
1381 const target = req.body.path;
1382 if (!target) return res.status(400).json({ error: 'path is required.' });
1383
1384 const { config, roots } = loadConfigAndRoots();
1385 const info = resolveRootForUser(target, roots, req.user, config);
1386 if (!info || !canWriteInfo(req.user, info))
1387 {
1388 return res.status(403).json({ error: 'Access denied.' });
1389 }
1390
1391 // Do not allow deleting a configured root itself
1392 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
1393 {
1394 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
1395 }
1396
1397 try
1398 {
1399 const stat = fs.statSync(target);
1400 if (stat.isDirectory())
1401 {
1402 fs.rmSync(target, { recursive: true, force: true });
1403 } else
1404 {
1405 fs.unlinkSync(target);
1406 }
1407 } catch (err)
1408 {
1409 return res.status(500).json({ error: err.message });
1410 }
1411
1412 // Clean up any DB meta entries under that path
1413 const db = getDb();
1414 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
1415 .run([target, target + path.sep + '%']);
1416
1417 res.json({ ok: true });
1418});
1419
1420// ---------------------------------------------------------------------------
1421// GET /api/files/folder-images?dir=<absolute-path>
1422// Returns images inside dir (recursive) that already have a cached thumbnail.
1423// Only images with a ready thumbnail are included (user constraint).
1424// ---------------------------------------------------------------------------
1425router.get('/folder-images', requireAuth, async (req, res) =>
1426{
1427 const dir = String(req.query.dir || '').trim();
1428 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1429
1430 const { config, roots } = loadConfigAndRoots();
1431 const info = resolveRootForUser(dir, roots, req.user, config);
1432 if (!info || !canReadInfo(req.user, info))
1433 {
1434 return res.status(403).json({ error: 'Access denied.' });
1435 }
1436
1437 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1438 {
1439 return res.status(404).json({ error: 'Directory not found.' });
1440 }
1441
1442 const images = await getImagesWithThumbnailsInDir(dir);
1443 // Filter out any that escaped to a different accessible root (safety check).
1444 const filtered = images.filter(({ filePath }) => isAccessiblePath(filePath, roots, req.user, config));
1445
1446 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1447});
1448
1449// ---------------------------------------------------------------------------
1450// GET /api/files/folder-icon?dir=<absolute-path>
1451// Returns the current icon source file for a folder (explicit or auto-first).
1452// ---------------------------------------------------------------------------
1453router.get('/folder-icon', requireAuth, async (req, res) =>
1454{
1455 const dir = String(req.query.dir || '').trim();
1456 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1457
1458 const { config, roots } = loadConfigAndRoots();
1459 const info = resolveRootForUser(dir, roots, req.user, config);
1460 if (!info || !canReadInfo(req.user, info))
1461 {
1462 return res.status(403).json({ error: 'Access denied.' });
1463 }
1464
1465 const sourceFile = await getFolderIconSourceFile(dir);
1466 if (!sourceFile) return res.json({ icon: null });
1467
1468 // Verify the source is still accessible within a configured root or user folder.
1469 if (!isAccessiblePath(sourceFile, roots, req.user, config)) return res.json({ icon: null });
1470
1471 res.json({ icon: { filePath: sourceFile } });
1472});
1473
1474// ---------------------------------------------------------------------------
1475// POST /api/files/folder-icon
1476// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
1477// Requires write access; the image must already have a cached thumbnail.
1478// ---------------------------------------------------------------------------
1479router.post('/folder-icon', requireAuth, async (req, res) =>
1480{
1481 const folderPath = String((req.body && req.body.folderPath) || '').trim();
1482 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
1483
1484 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1485
1486 const { config, roots } = loadConfigAndRoots();
1487 const info = resolveRootForUser(folderPath, roots, req.user, config);
1488 if (!info || !canWriteInfo(req.user, info))
1489 {
1490 return res.status(403).json({ error: 'Access denied.' });
1491 }
1492
1493 let stat;
1494 try { stat = fs.statSync(folderPath); }
1495 catch { return res.status(404).json({ error: 'Folder not found.' }); }
1496 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
1497
1498 if (rawImage !== null)
1499 {
1500 // Verify the image is inside a readable root or user folder.
1501 if (!isAccessiblePath(rawImage, roots, req.user, config)) return res.status(403).json({ error: 'Image not accessible.' });
1502
1503 // Must already have a cached thumbnail — only thumbnailed images can be selected.
1504 const thumb = await getCachedThumbnailInfo(rawImage);
1505 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
1506 }
1507
1508 await setFolderIconAssignment(folderPath, rawImage);
1509 res.json({ ok: true });
1510});
1511
1512// ---------------------------------------------------------------------------
1513// POST /api/files/copy
1514// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1515// Copies a file (not a directory) to the destination folder.
1516// Supports conflict: 'error' (default) | 'overwrite' | 'rename'
1517// ---------------------------------------------------------------------------
1518router.post('/copy', requireAuth, (req, res) =>
1519{
1520 const { from, toDir } = req.body;
1521 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1522 const targetName = req.body && req.body.targetName != null
1523 ? String(req.body.targetName).trim()
1524 : '';
1525 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1526 if (!['error', 'overwrite', 'rename'].includes(conflict))
1527 {
1528 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1529 }
1530
1531 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1532 {
1533 return res.status(400).json({ error: 'Invalid targetName.' });
1534 }
1535
1536 const { config, roots } = loadConfigAndRoots();
1537 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1538 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1539 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1540 if (!canReadInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1541 {
1542 return res.status(403).json({ error: 'Access denied.' });
1543 }
1544
1545 let sourceStat;
1546 try { sourceStat = fs.statSync(from); }
1547 catch { return res.status(404).json({ error: 'Source not found.' }); }
1548
1549 if (sourceStat.isDirectory())
1550 {
1551 return res.status(400).json({ error: 'Copying directories is not supported.' });
1552 }
1553
1554 if (!fs.existsSync(toDir) || !fs.statSync(toDir).isDirectory())
1555 {
1556 return res.status(404).json({ error: 'Destination directory not found.' });
1557 }
1558
1559 const requestedName = targetName || path.basename(from);
1560 const requestedDest = path.join(toDir, requestedName);
1561 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1562
1563 // Enforce per-user folder size limit when copying into a user folder.
1564 if (toInfo.isUserFolder)
1565 {
1566 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceStat.size);
1567 if (limitError) return res.status(413).json({ error: limitError });
1568 }
1569
1570 let dest = requestedDest;
1571 let resolvedConflict = 'none';
1572
1573 if (fs.existsSync(requestedDest))
1574 {
1575 if (conflict === 'error')
1576 {
1577 return res.status(409).json({ error: 'Destination already exists.' });
1578 }
1579 if (conflict === 'rename')
1580 {
1581 dest = pickNumberedPath(toDir, requestedName);
1582 resolvedConflict = 'rename';
1583 }
1584 if (conflict === 'overwrite')
1585 {
1586 resolvedConflict = 'overwrite';
1587 }
1588 }
1589
1590 try
1591 {
1592 fs.copyFileSync(from, dest);
1593 } catch (err)
1594 {
1595 return res.status(500).json({ error: err.message });
1596 }
1597
1598 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1599});
1600
1601module.exports = router;