BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

Fix My Folder access paths
timfa Tim Falken · pushed by timfa · 6 months ago
7c87f490 History
files.js 49.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, 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
511function movePathWithFallback (from, dest)
512{
513 const stat = fs.lstatSync(from);
514 try
515 {
516 fs.renameSync(from, dest);
517 return 'rename';
518 } catch (err)
519 {
520 try
521 {
522 if (stat.isDirectory())
523 {
524 fs.cpSync(from, dest, { recursive: true, force: true, preserveTimestamps: true });
525 } else
526 {
527 fs.copyFileSync(from, dest);
528 }
529 fs.rmSync(from, { recursive: true, force: true });
530 return 'copy-delete';
531 } catch (fallbackErr)
532 {
533 throw fallbackErr || err;
534 }
535 }
536}
537
538// ---------------------------------------------------------------------------
539// GET /api/files/roots
540// Returns the effective configured paths the user can read.
541// Also injects the user's personal folder when userPath is configured.
542// ---------------------------------------------------------------------------
543router.get('/roots', requireAuth, (req, res) =>
544{
545 const config = loadConfig();
546 const roots = getEffectivePaths(config.paths || []);
547 const rootAliases = rootAliasesFromConfig(config);
548
549 const readable = roots
550 .filter(r => canRead(req.user, path.basename(r)))
551 .map(r =>
552 {
553 const originalName = path.basename(r);
554 const alias = String(rootAliases[path.resolve(r)] || '').trim();
555 return {
556 label: alias || originalName,
557 path: r,
558 originalName,
559 alias: alias || null,
560 };
561 });
562
563 // Inject the user's personal folder when a userPath is configured.
564 if (req.user && req.user.username)
565 {
566 const userFolder = getUserFolderPath(config, req.user.username);
567 if (userFolder)
568 {
569 try { fs.mkdirSync(userFolder, { recursive: true }); } catch { /* non-fatal */ }
570 readable.unshift({
571 label: 'My Folder',
572 path: userFolder,
573 originalName: req.user.username,
574 alias: 'My Folder',
575 isUserFolder: true,
576 });
577 }
578 }
579
580 res.json({ roots: readable });
581});
582
583// ---------------------------------------------------------------------------
584// GET /api/files/root-access?rootPath=<absolute-root-path>
585// Returns users that can access a configured root and their mode (R / R+W).
586// ---------------------------------------------------------------------------
587router.get('/root-access', requireAuth, (req, res) =>
588{
589 const rootPath = String(req.query.rootPath || '').trim();
590 if (!rootPath)
591 {
592 return res.status(400).json({ error: 'rootPath is required.' });
593 }
594
595 const config = loadConfig();
596 const roots = getEffectivePaths(config.paths || []);
597 const info = resolveRoot(rootPath, roots);
598 if (!info) return res.status(403).json({ error: 'Access denied.' });
599 if (!sameResolvedPath(rootPath, info.root))
600 {
601 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
602 }
603 if (!canRead(req.user, info.label))
604 {
605 return res.status(403).json({ error: 'Access denied.' });
606 }
607
608 const db = getDb();
609 const rows = db.prepare('SELECT username, is_admin, permissions FROM users').all();
610 const users = [];
611
612 for (const row of rows)
613 {
614 if (row.is_admin === 1)
615 {
616 users.push({ username: row.username, mode: 'R+W' });
617 continue;
618 }
619
620 let permissions = {};
621 try
622 {
623 permissions = JSON.parse(row.permissions || '{}');
624 } catch
625 {
626 permissions = {};
627 }
628
629 const perm = permissions[info.label];
630 if (!perm || typeof perm !== 'object') continue;
631 const canWriteRoot = !!perm.write;
632 const canReadRoot = !!perm.read || canWriteRoot;
633 if (!canReadRoot) continue;
634 users.push({ username: row.username, mode: canWriteRoot ? 'R+W' : 'R' });
635 }
636
637 users.sort((a, b) =>
638 {
639 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
640 const byMode = modeRank(a.mode) - modeRank(b.mode);
641 if (byMode !== 0) return byMode;
642 return String(a.username).localeCompare(String(b.username));
643 });
644
645 const rootAliases = rootAliasesFromConfig(config);
646 const alias = String(rootAliases[path.resolve(info.root)] || '').trim();
647 res.json({
648 root: {
649 path: info.root,
650 label: alias || info.label,
651 originalName: info.label,
652 alias: alias || null,
653 },
654 users,
655 });
656});
657
658// ---------------------------------------------------------------------------
659// POST /api/files/root-alias
660// Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
661// Sets a display-only alias for a configured root.
662// ---------------------------------------------------------------------------
663router.post('/root-alias', requireAuth, (req, res) =>
664{
665 const rootPath = String(req.body && req.body.rootPath || '').trim();
666 const alias = String(req.body && req.body.alias || '').trim();
667 if (!rootPath || !alias)
668 {
669 return res.status(400).json({ error: 'rootPath and alias are required.' });
670 }
671
672 const roots = effectivePaths();
673 const info = resolveRoot(rootPath, roots);
674 if (!info) return res.status(403).json({ error: 'Access denied.' });
675 if (!sameResolvedPath(rootPath, info.root))
676 {
677 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
678 }
679 if (!canWrite(req.user, info.label))
680 {
681 return res.status(403).json({ error: 'Access denied.' });
682 }
683
684 const config = loadConfig();
685 const rootAliases = rootAliasesFromConfig(config);
686 const key = path.resolve(info.root);
687 if (alias === info.label)
688 {
689 delete rootAliases[key];
690 } else
691 {
692 rootAliases[key] = alias;
693 }
694 config.rootAliases = rootAliases;
695 saveConfig(config);
696
697 res.json({
698 ok: true,
699 root: {
700 path: info.root,
701 label: alias,
702 originalName: info.label,
703 alias,
704 },
705 });
706});
707
708// ---------------------------------------------------------------------------
709// GET /api/files/list?dir=<absolute-path>
710// Lists files and folders in the given directory.
711// ---------------------------------------------------------------------------
712router.get('/list', requireAuth, (req, res) =>
713{
714 const dir = req.query.dir;
715 if (!dir) return res.status(400).json({ error: 'dir is required.' });
716
717 const { config, roots } = loadConfigAndRoots();
718 const info = resolveRootForUser(dir, roots, req.user, config);
719 if (!info || !canReadInfo(req.user, info)) return res.status(403).json({ error: 'Access denied.' });
720
721 let entries;
722 try
723 {
724 entries = fs.readdirSync(dir, { withFileTypes: true });
725 } catch
726 {
727 return res.status(404).json({ error: 'Directory not found.' });
728 }
729
730 const items = entries.map(e =>
731 {
732 const fullPath = path.join(dir, e.name);
733 let size = null;
734 let mtime = null;
735 try
736 {
737 const stat = fs.statSync(fullPath);
738 size = stat.size;
739 mtime = stat.mtime.toISOString();
740 } catch { /* ignore */ }
741
742 return {
743 name: e.name,
744 isDir: e.isDirectory(),
745 size,
746 mtime,
747 path: fullPath,
748 };
749 });
750
751 res.json({ items });
752});
753
754// ---------------------------------------------------------------------------
755// GET /api/files/meta?file=<absolute-path>
756// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
757// ---------------------------------------------------------------------------
758router.get('/meta', requireAuth, async (req, res) =>
759{
760 const file = req.query.file;
761 if (!file) return res.status(400).json({ error: 'file is required.' });
762
763 const { config, roots } = loadConfigAndRoots();
764 const info = resolveRootForUser(file, roots, req.user, config);
765 if (!info || !canReadInfo(req.user, info))
766 {
767 return res.status(403).json({ error: 'Access denied.' });
768 }
769
770 let stat;
771 try
772 {
773 stat = fs.statSync(file);
774 } catch
775 {
776 return res.status(404).json({ error: 'File not found.' });
777 }
778
779 const db = getDb();
780 let meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
781
782 // Lazily compute and persist the SHA-256 hash when it is absent.
783 let sha256 = meta ? (meta.sha256 || null) : null;
784 if (!sha256 && !stat.isDirectory())
785 {
786 try
787 {
788 sha256 = await computeFileSha256(file);
789 if (meta)
790 {
791 db.prepare('UPDATE file_meta SET sha256 = ? WHERE file_path = ?').run([sha256, file]);
792 } else
793 {
794 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
795 .run([file, '', '[]', sha256]);
796 meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
797 }
798 } catch
799 {
800 // Non-fatal — hash will be retried next time.
801 }
802 }
803
804 res.json({
805 name: path.basename(file),
806 size: stat.size,
807 mtime: stat.mtime.toISOString(),
808 uploader: meta ? meta.uploader : '',
809 downloaders: meta ? parseJsonArray(meta.downloaders) : [],
810 watchedBy: meta ? parseJsonObject(meta.watched_by) : {},
811 sha256: sha256 || null,
812 });
813});
814
815// ---------------------------------------------------------------------------
816// GET /api/files/duplicates?file=<absolute-path>
817// Returns other files with the same SHA-256 hash that the user can access.
818// ---------------------------------------------------------------------------
819router.get('/duplicates', requireAuth, (req, res) =>
820{
821 const file = req.query.file;
822 if (!file) return res.status(400).json({ error: 'file is required.' });
823
824 const { config, roots } = loadConfigAndRoots();
825 const info = resolveRootForUser(file, roots, req.user, config);
826 if (!info || !canReadInfo(req.user, info))
827 {
828 return res.status(403).json({ error: 'Access denied.' });
829 }
830
831 const db = getDb();
832 const row = db.prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([file]);
833 const hash = row ? (row.sha256 || null) : null;
834 if (!hash)
835 {
836 return res.json({ duplicates: [] });
837 }
838
839 // All other files sharing the same hash.
840 const candidates = db.prepare(
841 'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',
842 ).all([hash, file]);
843
844 const duplicates = [];
845 for (const { file_path } of candidates)
846 {
847 // Only return files inside a root the user can access and that still exist on disk.
848 const dupInfo = resolveRootForUser(file_path, roots, req.user, config);
849 if (!dupInfo || !canReadInfo(req.user, dupInfo)) continue;
850 if (!fs.existsSync(file_path)) continue;
851
852 const rel = path.relative(dupInfo.root, file_path);
853 const relativePath = rel && rel !== '' ? rel : path.basename(file_path);
854
855 duplicates.push({
856 path: file_path,
857 name: path.basename(file_path),
858 dir: path.dirname(file_path),
859 rootPath: dupInfo.root,
860 relativePath,
861 });
862 }
863
864 res.json({ duplicates });
865});
866
867// ---------------------------------------------------------------------------
868// GET /api/files/space?dir=<absolute-path>
869// Returns recursive used bytes for dir and available bytes on its root fs.
870// ---------------------------------------------------------------------------
871router.get('/space', requireAuth, (req, res) =>
872{
873 const dir = req.query.dir;
874 if (!dir) return res.status(400).json({ error: 'dir is required.' });
875
876 const { config, roots } = loadConfigAndRoots();
877 const info = resolveRootForUser(dir, roots, req.user, config);
878 if (!info || !canReadInfo(req.user, info))
879 {
880 return res.status(403).json({ error: 'Access denied.' });
881 }
882
883 if (!fs.existsSync(dir))
884 {
885 return res.status(404).json({ error: 'Path not found.' });
886 }
887
888 const usedBytes = getRecursiveSize(dir);
889 const freeBytes = getFreeBytes(info.root);
890 const userLimitBytes = info.isUserFolder ? getUserFolderSizeLimit(config) : null;
891 const userFreeBytes = userLimitBytes == null ? null : Math.max(0, userLimitBytes - usedBytes);
892 res.json({
893 usedBytes,
894 freeBytes,
895 userLimitBytes,
896 userFreeBytes,
897 rootPath: info.root,
898 rootLabel: info.label,
899 });
900});
901
902// ---------------------------------------------------------------------------
903// GET /api/files/download?file=<absolute-path>
904// Streams the file to the client; records the download.
905// ---------------------------------------------------------------------------
906router.get('/download', requireAuth, (req, res) =>
907{
908 const file = req.query.file;
909 if (!file) return res.status(400).json({ error: 'file is required.' });
910
911 const { config, roots } = loadConfigAndRoots();
912 const info = resolveRootForUser(file, roots, req.user, config);
913 if (!info || !canReadInfo(req.user, info))
914 {
915 return res.status(403).json({ error: 'Access denied.' });
916 }
917
918 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
919 {
920 return res.status(404).json({ error: 'File not found.' });
921 }
922
923 // Record download
924 const db = getDb();
925 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
926 if (meta)
927 {
928 const downloaders = parseJsonArray(meta.downloaders);
929 if (!downloaders.includes(req.user.username))
930 {
931 downloaders.push(req.user.username);
932 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
933 .run([JSON.stringify(downloaders), file]);
934 }
935 } else
936 {
937 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
938 .run([file, '', JSON.stringify([req.user.username]), '{}']);
939 }
940
941 res.download(file, path.basename(file));
942});
943
944// ---------------------------------------------------------------------------
945// POST /api/files/watch-progress
946// Body: { filePath: <absolute-path>, progress: <0..1> }
947// Records per-user video watch state for sidebar display.
948// ---------------------------------------------------------------------------
949router.post('/watch-progress', requireAuth, (req, res) =>
950{
951 const filePath = String(req.body && req.body.filePath || '').trim();
952 const progress = Number(req.body && req.body.progress);
953 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
954
955 const status = watchStatusForProgress(progress);
956 if (!status)
957 {
958 return res.json({ ok: true, updated: false });
959 }
960
961 const { config, roots } = loadConfigAndRoots();
962 const info = resolveRootForUser(filePath, roots, req.user, config);
963 if (!info || !canReadInfo(req.user, info))
964 {
965 return res.status(403).json({ error: 'Access denied.' });
966 }
967
968 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
969 {
970 return res.status(404).json({ error: 'File not found.' });
971 }
972
973 const db = getDb();
974 const row = db.prepare('SELECT uploader, downloaders, watched_by FROM file_meta WHERE file_path = ?').get([filePath]);
975 const watchedBy = parseJsonObject(row && row.watched_by);
976 const prev = String(watchedBy[req.user.username] || '').toLowerCase();
977 const next = prev === 'fully' ? 'fully' : status;
978 if (prev === next)
979 {
980 return res.json({ ok: true, updated: false, status: next });
981 }
982
983 watchedBy[req.user.username] = next;
984 if (row)
985 {
986 db.prepare('UPDATE file_meta SET watched_by = ? WHERE file_path = ?')
987 .run([JSON.stringify(watchedBy), filePath]);
988 } else
989 {
990 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
991 .run([filePath, '', '[]', JSON.stringify(watchedBy)]);
992 }
993
994 res.json({ ok: true, updated: true, status: next });
995});
996
997// ---------------------------------------------------------------------------
998// POST /api/files/video-stream
999// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
1000// ---------------------------------------------------------------------------
1001router.post('/video-stream', requireAuth, async (req, res, next) =>
1002{
1003 try
1004 {
1005 const filePath = String(req.body?.filePath || '').trim();
1006 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
1007
1008 const { config, roots } = loadConfigAndRoots();
1009 const info = resolveRootForUser(filePath, roots, req.user, config);
1010 if (!info || !canReadInfo(req.user, info))
1011 {
1012 return res.status(403).json({ error: 'Access denied.' });
1013 }
1014
1015 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1016 {
1017 return res.status(404).json({ error: 'File not found.' });
1018 }
1019
1020 const session = await createVideoStreamSession(filePath);
1021 res.json({
1022 sessionId: session.sessionId,
1023 playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
1024 durationSeconds: session.durationSeconds || null,
1025 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
1026 subtitleTracks: session.subtitleTracks.map((track) => ({
1027 label: track.label,
1028 language: track.language,
1029 default: !!track.isDefault,
1030 src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`,
1031 })),
1032 });
1033 } catch (err)
1034 {
1035 next(err);
1036 }
1037});
1038
1039// ---------------------------------------------------------------------------
1040// GET /api/files/video-stream/:sessionId/:assetPath(*)
1041// Streams HLS assets for a previously created short-lived video session.
1042// ---------------------------------------------------------------------------
1043router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>
1044{
1045 try
1046 {
1047 await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res);
1048 } catch (err)
1049 {
1050 next(err);
1051 }
1052});
1053
1054// ---------------------------------------------------------------------------
1055// DELETE /api/files/video-stream/:sessionId
1056// Authenticated. Explicitly releases an active short-lived video session.
1057// ---------------------------------------------------------------------------
1058router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>
1059{
1060 const sessionId = String(req.params.sessionId || '').trim();
1061 if (!sessionId) return res.status(400).json({ error: 'sessionId is required.' });
1062
1063 releaseVideoStreamSession(sessionId);
1064 res.json({ ok: true });
1065});
1066
1067// ---------------------------------------------------------------------------
1068// GET /api/files/download-zip?dir=<absolute-path>
1069// Authenticated. Streams a zip of the given directory.
1070// ---------------------------------------------------------------------------
1071router.get('/download-zip', requireAuth, async (req, res) =>
1072{
1073 const dir = req.query.dir;
1074 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1075
1076 const { config, roots } = loadConfigAndRoots();
1077 const info = resolveRootForUser(dir, roots, req.user, config);
1078 if (!info || !canReadInfo(req.user, info))
1079 {
1080 return res.status(403).json({ error: 'Access denied.' });
1081 }
1082
1083 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1084 {
1085 return res.status(404).json({ error: 'Directory not found.' });
1086 }
1087
1088 // Use a hash of the dir path as cache key so concurrent users share the cache.
1089 const cacheKey = crypto.createHash('sha256').update(dir).digest('hex');
1090 try
1091 {
1092 const zipPath = await buildZip(dir, cacheKey);
1093 const zipName = `${path.basename(dir)}.zip`;
1094 res.download(zipPath, zipName);
1095 } catch (err)
1096 {
1097 res.status(500).json({ error: 'Failed to create zip archive.' });
1098 }
1099});
1100
1101// ---------------------------------------------------------------------------
1102// GET /api/files/thumbnail?file=<absolute-path>
1103// Returns a pre-generated cached thumbnail if present.
1104// ---------------------------------------------------------------------------
1105router.get('/thumbnail', requireAuth, async (req, res) =>
1106{
1107 const file = req.query.file;
1108 if (!file) return res.status(400).json({ error: 'file is required.' });
1109
1110 const { config, roots } = loadConfigAndRoots();
1111 const info = resolveRootForUser(file, roots, req.user, config);
1112 if (!info || !canReadInfo(req.user, info))
1113 {
1114 return res.status(403).json({ error: 'Access denied.' });
1115 }
1116
1117 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1118 {
1119 return res.status(404).json({ error: 'File not found.' });
1120 }
1121
1122 const thumb = await getCachedThumbnailInfo(file);
1123 if (!thumb)
1124 {
1125 return res.status(404).json({ error: 'Thumbnail not ready.' });
1126 }
1127
1128 res.type(thumb.contentType);
1129 res.set('Cache-Control', 'private, max-age=10');
1130 res.sendFile(thumb.thumbPath);
1131});
1132
1133// ---------------------------------------------------------------------------
1134// POST /api/files/upload?dir=<absolute-path>
1135// Accepts multipart file upload.
1136// ---------------------------------------------------------------------------
1137router.post('/upload', requireAuth, (req, res, next) =>
1138{
1139 const dir = req.query.dir;
1140 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1141
1142 const { config, roots } = loadConfigAndRoots();
1143 const info = resolveRootForUser(dir, roots, req.user, config);
1144 if (!info || !canWriteInfo(req.user, info))
1145 {
1146 return res.status(403).json({ error: 'Access denied.' });
1147 }
1148
1149 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1150 {
1151 return res.status(404).json({ error: 'Directory not found.' });
1152 }
1153
1154 const announcedSize = Number(req.header('x-upload-size') || 0);
1155 if (Number.isFinite(announcedSize) && announcedSize > 0)
1156 {
1157 const freeBytes = getFreeBytes(info.root);
1158 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
1159 {
1160 return res.status(413).json({
1161 error: 'Upload too large for remaining free space on selected root.',
1162 freeBytes,
1163 requiredBytes: announcedSize,
1164 });
1165 }
1166 }
1167
1168 // Enforce per-user folder size limit when uploading to a user folder.
1169 if (info.isUserFolder)
1170 {
1171 const addBytes = announcedSize > 0 ? announcedSize : 0;
1172 const limitError = checkUserFolderSizeLimit(config, req.user.username, addBytes);
1173 if (limitError) return res.status(413).json({ error: limitError });
1174 }
1175
1176 req._uploadDir = dir;
1177
1178 upload.array('files')(req, res, async (err) =>
1179 {
1180 if (err) return res.status(500).json({ error: err.message });
1181
1182 const db = getDb();
1183 for (const f of (req.files || []))
1184 {
1185 const filePath = path.join(dir, f.originalname);
1186
1187 let sha256 = null;
1188 try
1189 {
1190 sha256 = await computeFileSha256(filePath);
1191 } catch
1192 {
1193 // Non-fatal — hash can be computed lazily when the file is accessed.
1194 }
1195
1196 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
1197 if (existing)
1198 {
1199 db.prepare('UPDATE file_meta SET uploader = ?, sha256 = ? WHERE file_path = ?')
1200 .run([req.user.username, sha256, filePath]);
1201 } else
1202 {
1203 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1204 .run([filePath, req.user.username, '[]', sha256]);
1205 }
1206 }
1207 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
1208 });
1209});
1210
1211// ---------------------------------------------------------------------------
1212// POST /api/files/rename
1213// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
1214// ---------------------------------------------------------------------------
1215router.post('/rename', requireAuth, (req, res) =>
1216{
1217 const { from, to } = req.body;
1218 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
1219
1220 // Prevent path traversal in the new name
1221 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
1222 {
1223 return res.status(400).json({ error: 'Invalid name.' });
1224 }
1225
1226 const { config, roots } = loadConfigAndRoots();
1227 const info = resolveRootForUser(from, roots, req.user, config);
1228 if (!info || !canWriteInfo(req.user, info))
1229 {
1230 return res.status(403).json({ error: 'Access denied.' });
1231 }
1232
1233 const dest = path.join(path.dirname(from), to);
1234
1235 // Ensure dest is still inside the same accessible root or user folder.
1236 if (!isAccessiblePath(dest, roots, req.user, config))
1237 {
1238 return res.status(403).json({ error: 'Access denied.' });
1239 }
1240
1241 try
1242 {
1243 movePathWithFallback(from, dest);
1244 } catch (err)
1245 {
1246 return res.status(500).json({ error: err.message });
1247 }
1248
1249 rewriteMetaPaths(from, dest);
1250
1251 res.json({ ok: true });
1252});
1253
1254// ---------------------------------------------------------------------------
1255// POST /api/files/move
1256// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1257// ---------------------------------------------------------------------------
1258router.post('/move', requireAuth, (req, res) =>
1259{
1260 const { from, toDir } = req.body;
1261 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1262 const targetName = req.body && req.body.targetName != null
1263 ? String(req.body.targetName).trim()
1264 : '';
1265 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1266 if (!['error', 'overwrite', 'rename'].includes(conflict))
1267 {
1268 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1269 }
1270
1271 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1272 {
1273 return res.status(400).json({ error: 'Invalid targetName.' });
1274 }
1275
1276 const { config, roots } = loadConfigAndRoots();
1277 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1278 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1279 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1280 if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1281 {
1282 return res.status(403).json({ error: 'Access denied.' });
1283 }
1284
1285 let sourceStat;
1286 let destStat;
1287 try
1288 {
1289 sourceStat = fs.statSync(from);
1290 destStat = fs.statSync(toDir);
1291 } catch
1292 {
1293 return res.status(404).json({ error: 'Source or destination not found.' });
1294 }
1295
1296 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
1297
1298 const requestedName = targetName || path.basename(from);
1299 const requestedDest = path.join(toDir, requestedName);
1300 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1301
1302 // Enforce per-user folder size limit when moving into a user folder.
1303 if (toInfo.isUserFolder)
1304 {
1305 const sourceSize = getRecursiveSize(from);
1306 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceSize);
1307 if (limitError) return res.status(413).json({ error: limitError });
1308 }
1309 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
1310 {
1311 return res.status(400).json({ error: 'Cannot move onto itself.' });
1312 }
1313 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
1314 {
1315 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
1316 }
1317
1318 let dest = requestedDest;
1319 let resolvedConflict = 'none';
1320
1321 if (fs.existsSync(requestedDest))
1322 {
1323 if (conflict === 'error')
1324 {
1325 return res.status(409).json({ error: 'Destination already exists.' });
1326 }
1327
1328 if (conflict === 'rename')
1329 {
1330 dest = pickNumberedPath(toDir, requestedName);
1331 resolvedConflict = 'rename';
1332 }
1333
1334 if (conflict === 'overwrite')
1335 {
1336 try
1337 {
1338 removePathRecursive(requestedDest);
1339 } catch (err)
1340 {
1341 return res.status(500).json({ error: err.message });
1342 }
1343 resolvedConflict = 'overwrite';
1344 }
1345 }
1346
1347 if (sameResolvedPath(from, dest))
1348 {
1349 return res.status(400).json({ error: 'Cannot move onto itself.' });
1350 }
1351
1352 try
1353 {
1354 movePathWithFallback(from, dest);
1355 } catch (err)
1356 {
1357 return res.status(500).json({ error: err.message });
1358 }
1359
1360 rewriteMetaPaths(from, dest);
1361 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1362});
1363
1364// ---------------------------------------------------------------------------
1365// POST /api/files/mkdir
1366// Body: { dir: <absolute-path>, name: <folder-name> }
1367// ---------------------------------------------------------------------------
1368router.post('/mkdir', requireAuth, (req, res) =>
1369{
1370 const { dir, name } = req.body;
1371 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
1372
1373 if (path.basename(name) !== name)
1374 {
1375 return res.status(400).json({ error: 'Invalid folder name.' });
1376 }
1377
1378 const { config, roots } = loadConfigAndRoots();
1379 const info = resolveRootForUser(dir, roots, req.user, config);
1380 if (!info || !canWriteInfo(req.user, info))
1381 {
1382 return res.status(403).json({ error: 'Access denied.' });
1383 }
1384
1385 const newDir = path.join(dir, name);
1386 if (!isAccessiblePath(newDir, roots, req.user, config))
1387 {
1388 return res.status(403).json({ error: 'Access denied.' });
1389 }
1390
1391 try
1392 {
1393 fs.mkdirSync(newDir, { recursive: false });
1394 } catch (err)
1395 {
1396 return res.status(500).json({ error: err.message });
1397 }
1398
1399 res.json({ ok: true, path: newDir });
1400});
1401
1402// ---------------------------------------------------------------------------
1403// POST /api/files/delete
1404// Body: { path: <absolute-path> }
1405// ---------------------------------------------------------------------------
1406router.post('/delete', requireAuth, (req, res) =>
1407{
1408 const target = req.body.path;
1409 if (!target) return res.status(400).json({ error: 'path is required.' });
1410
1411 const { config, roots } = loadConfigAndRoots();
1412 const info = resolveRootForUser(target, roots, req.user, config);
1413 if (!info || !canWriteInfo(req.user, info))
1414 {
1415 return res.status(403).json({ error: 'Access denied.' });
1416 }
1417
1418 // Do not allow deleting a configured root itself
1419 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
1420 {
1421 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
1422 }
1423
1424 try
1425 {
1426 const stat = fs.statSync(target);
1427 if (stat.isDirectory())
1428 {
1429 fs.rmSync(target, { recursive: true, force: true });
1430 } else
1431 {
1432 fs.unlinkSync(target);
1433 }
1434 } catch (err)
1435 {
1436 return res.status(500).json({ error: err.message });
1437 }
1438
1439 // Clean up any DB meta entries under that path
1440 const db = getDb();
1441 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
1442 .run([target, target + path.sep + '%']);
1443
1444 res.json({ ok: true });
1445});
1446
1447// ---------------------------------------------------------------------------
1448// GET /api/files/folder-images?dir=<absolute-path>
1449// Returns images inside dir (recursive) that already have a cached thumbnail.
1450// Only images with a ready thumbnail are included (user constraint).
1451// ---------------------------------------------------------------------------
1452router.get('/folder-images', requireAuth, async (req, res) =>
1453{
1454 const dir = String(req.query.dir || '').trim();
1455 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1456
1457 const { config, roots } = loadConfigAndRoots();
1458 const info = resolveRootForUser(dir, roots, req.user, config);
1459 if (!info || !canReadInfo(req.user, info))
1460 {
1461 return res.status(403).json({ error: 'Access denied.' });
1462 }
1463
1464 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1465 {
1466 return res.status(404).json({ error: 'Directory not found.' });
1467 }
1468
1469 const images = await getImagesWithThumbnailsInDir(dir);
1470 // Filter out any that escaped to a different accessible root (safety check).
1471 const filtered = images.filter(({ filePath }) => isAccessiblePath(filePath, roots, req.user, config));
1472
1473 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1474});
1475
1476// ---------------------------------------------------------------------------
1477// GET /api/files/folder-icon?dir=<absolute-path>
1478// Returns the current icon source file for a folder (explicit or auto-first).
1479// ---------------------------------------------------------------------------
1480router.get('/folder-icon', requireAuth, async (req, res) =>
1481{
1482 const dir = String(req.query.dir || '').trim();
1483 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1484
1485 const { config, roots } = loadConfigAndRoots();
1486 const info = resolveRootForUser(dir, roots, req.user, config);
1487 if (!info || !canReadInfo(req.user, info))
1488 {
1489 return res.status(403).json({ error: 'Access denied.' });
1490 }
1491
1492 const sourceFile = await getFolderIconSourceFile(dir);
1493 if (!sourceFile) return res.json({ icon: null });
1494
1495 // Verify the source is still accessible within a configured root or user folder.
1496 if (!isAccessiblePath(sourceFile, roots, req.user, config)) return res.json({ icon: null });
1497
1498 res.json({ icon: { filePath: sourceFile } });
1499});
1500
1501// ---------------------------------------------------------------------------
1502// POST /api/files/folder-icon
1503// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
1504// Requires write access; the image must already have a cached thumbnail.
1505// ---------------------------------------------------------------------------
1506router.post('/folder-icon', requireAuth, async (req, res) =>
1507{
1508 const folderPath = String((req.body && req.body.folderPath) || '').trim();
1509 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
1510
1511 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1512
1513 const { config, roots } = loadConfigAndRoots();
1514 const info = resolveRootForUser(folderPath, roots, req.user, config);
1515 if (!info || !canWriteInfo(req.user, info))
1516 {
1517 return res.status(403).json({ error: 'Access denied.' });
1518 }
1519
1520 let stat;
1521 try { stat = fs.statSync(folderPath); }
1522 catch { return res.status(404).json({ error: 'Folder not found.' }); }
1523 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
1524
1525 if (rawImage !== null)
1526 {
1527 // Verify the image is inside a readable root or user folder.
1528 if (!isAccessiblePath(rawImage, roots, req.user, config)) return res.status(403).json({ error: 'Image not accessible.' });
1529
1530 // Must already have a cached thumbnail — only thumbnailed images can be selected.
1531 const thumb = await getCachedThumbnailInfo(rawImage);
1532 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
1533 }
1534
1535 await setFolderIconAssignment(folderPath, rawImage);
1536 res.json({ ok: true });
1537});
1538
1539// ---------------------------------------------------------------------------
1540// POST /api/files/copy
1541// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1542// Copies a file (not a directory) to the destination folder.
1543// Supports conflict: 'error' (default) | 'overwrite' | 'rename'
1544// ---------------------------------------------------------------------------
1545router.post('/copy', requireAuth, (req, res) =>
1546{
1547 const { from, toDir } = req.body;
1548 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1549 const targetName = req.body && req.body.targetName != null
1550 ? String(req.body.targetName).trim()
1551 : '';
1552 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1553 if (!['error', 'overwrite', 'rename'].includes(conflict))
1554 {
1555 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1556 }
1557
1558 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1559 {
1560 return res.status(400).json({ error: 'Invalid targetName.' });
1561 }
1562
1563 const { config, roots } = loadConfigAndRoots();
1564 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1565 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1566 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1567 if (!canReadInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1568 {
1569 return res.status(403).json({ error: 'Access denied.' });
1570 }
1571
1572 let sourceStat;
1573 try { sourceStat = fs.statSync(from); }
1574 catch { return res.status(404).json({ error: 'Source not found.' }); }
1575
1576 if (sourceStat.isDirectory())
1577 {
1578 return res.status(400).json({ error: 'Copying directories is not supported.' });
1579 }
1580
1581 if (!fs.existsSync(toDir) || !fs.statSync(toDir).isDirectory())
1582 {
1583 return res.status(404).json({ error: 'Destination directory not found.' });
1584 }
1585
1586 const requestedName = targetName || path.basename(from);
1587 const requestedDest = path.join(toDir, requestedName);
1588 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1589
1590 // Enforce per-user folder size limit when copying into a user folder.
1591 if (toInfo.isUserFolder)
1592 {
1593 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceStat.size);
1594 if (limitError) return res.status(413).json({ error: limitError });
1595 }
1596
1597 let dest = requestedDest;
1598 let resolvedConflict = 'none';
1599
1600 if (fs.existsSync(requestedDest))
1601 {
1602 if (conflict === 'error')
1603 {
1604 return res.status(409).json({ error: 'Destination already exists.' });
1605 }
1606 if (conflict === 'rename')
1607 {
1608 dest = pickNumberedPath(toDir, requestedName);
1609 resolvedConflict = 'rename';
1610 }
1611 if (conflict === 'overwrite')
1612 {
1613 resolvedConflict = 'overwrite';
1614 }
1615 }
1616
1617 try
1618 {
1619 fs.copyFileSync(from, dest);
1620 } catch (err)
1621 {
1622 return res.status(500).json({ error: err.message });
1623 }
1624
1625 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1626});
1627
1628module.exports = router;