BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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