BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

pip
timfa Tim Falken · pushed by timfa · 6 months ago
aefbcaaa History
files.js 27.4 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const path = require('path');
5const fs = require('fs');
6const multer = require('multer');
7const router = express.Router();
8
9const { getDb } = require('../db');
10const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
11const { requireAuth } = require('../auth');
12const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
13
14// ---------------------------------------------------------------------------
15// Multer storage — files are written directly to the target directory
16// ---------------------------------------------------------------------------
17const storage = multer.diskStorage({
18 destination (req, file, cb)
19 {
20 // The target directory is resolved in the route handler, so we stash it
21 // during the multer middleware call via req._uploadDir.
22 cb(null, req._uploadDir);
23 },
24 filename (req, file, cb)
25 {
26 cb(null, file.originalname);
27 },
28});
29
30const upload = multer({
31 storage,
32 limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB
33});
34
35// ---------------------------------------------------------------------------
36// Helpers
37// ---------------------------------------------------------------------------
38
39function effectivePaths ()
40{
41 return getEffectivePaths(loadConfig().paths || []);
42}
43
44function rootAliasesFromConfig (config)
45{
46 if (!config || typeof config !== 'object') return {};
47 if (!config.rootAliases || typeof config.rootAliases !== 'object') return {};
48 return config.rootAliases;
49}
50
51function getFreeBytes (targetPath)
52{
53 if (typeof fs.statfsSync !== 'function') return null;
54 try
55 {
56 const stat = fs.statfsSync(targetPath);
57 if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null;
58 return stat.bavail * stat.bsize;
59 } catch
60 {
61 return null;
62 }
63}
64
65function getRecursiveSize (targetPath)
66{
67 try
68 {
69 const stat = fs.statSync(targetPath);
70 if (!stat.isDirectory()) return stat.size;
71 } catch
72 {
73 return 0;
74 }
75
76 let total = 0;
77 let entries = [];
78 try
79 {
80 entries = fs.readdirSync(targetPath, { withFileTypes: true });
81 } catch
82 {
83 return 0;
84 }
85
86 for (const entry of entries)
87 {
88 const child = path.join(targetPath, entry.name);
89 if (entry.isDirectory())
90 {
91 total += getRecursiveSize(child);
92 continue;
93 }
94 try
95 {
96 total += fs.statSync(child).size;
97 } catch
98 {
99 // Ignore files that disappear during traversal.
100 }
101 }
102
103 return total;
104}
105
106/**
107 * Verify that the user has read access to the given configured-path label.
108 * `pathLabel` is the base-name of the effective path (shown in the UI).
109 */
110function canRead (user, pathLabel)
111{
112 if (user.isAdmin) return true;
113 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
114}
115
116function canWrite (user, pathLabel)
117{
118 if (user.isAdmin) return true;
119 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
120}
121
122/**
123 * Given an absolute path and the effective-paths list, return
124 * { root, label } where label is the base-name of the root, or null.
125 */
126function resolveRoot (absPath, roots)
127{
128 const matchedRoot = getAllowedRoot(absPath, roots);
129 if (!matchedRoot) return null;
130 return { root: matchedRoot, label: path.basename(matchedRoot) };
131}
132
133function sameResolvedPath (a, b)
134{
135 return path.resolve(String(a || '')) === path.resolve(String(b || ''));
136}
137
138function pathInsideResolved (child, root)
139{
140 const relative = path.relative(path.resolve(root), path.resolve(child));
141 return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
142}
143
144function rewriteMetaPaths (fromPath, toPath)
145{
146 const db = getDb();
147 const rows = db.prepare('SELECT file_path, uploader, downloaders FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
148 .all([fromPath, fromPath + path.sep + '%']);
149
150 if (!rows.length) return;
151
152 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
153 const upsert = db.prepare(`
154 INSERT INTO file_meta (file_path, uploader, downloaders)
155 VALUES (?, ?, ?)
156 ON CONFLICT(file_path) DO UPDATE SET
157 uploader = excluded.uploader,
158 downloaders = excluded.downloaders
159 `);
160
161 for (const row of rows)
162 {
163 const nextPath = row.file_path === fromPath
164 ? toPath
165 : toPath + row.file_path.slice(fromPath.length);
166 del.run([row.file_path]);
167 upsert.run([nextPath, row.uploader, row.downloaders]);
168 }
169}
170
171function splitNameExt (name)
172{
173 const dot = String(name || '').lastIndexOf('.');
174 if (dot <= 0) return { stem: String(name || ''), ext: '' };
175 return {
176 stem: String(name).slice(0, dot),
177 ext: String(name).slice(dot),
178 };
179}
180
181function pickNumberedPath (dir, requestedName)
182{
183 const parsed = splitNameExt(requestedName);
184 const stem = parsed.stem || 'file';
185 const ext = parsed.ext || '';
186 let index = 1;
187
188 while (index <= 10000)
189 {
190 const candidateName = `${stem} (${index})${ext}`;
191 const candidatePath = path.join(dir, candidateName);
192 if (!fs.existsSync(candidatePath)) return candidatePath;
193 index++;
194 }
195
196 throw new Error('Could not generate a free destination name.');
197}
198
199function removePathRecursive (targetPath)
200{
201 const stat = fs.lstatSync(targetPath);
202 if (stat.isDirectory())
203 {
204 fs.rmSync(targetPath, { recursive: true, force: true });
205 } else
206 {
207 fs.unlinkSync(targetPath);
208 }
209}
210
211// ---------------------------------------------------------------------------
212// GET /api/files/roots
213// Returns the effective configured paths the user can read.
214// ---------------------------------------------------------------------------
215router.get('/roots', requireAuth, (req, res) =>
216{
217 const config = loadConfig();
218 const roots = getEffectivePaths(config.paths || []);
219 const rootAliases = rootAliasesFromConfig(config);
220
221 const readable = roots
222 .filter(r => canRead(req.user, path.basename(r)))
223 .map(r =>
224 {
225 const originalName = path.basename(r);
226 const alias = String(rootAliases[path.resolve(r)] || '').trim();
227 return {
228 label: alias || originalName,
229 path: r,
230 originalName,
231 alias: alias || null,
232 };
233 });
234 res.json({ roots: readable });
235});
236
237// ---------------------------------------------------------------------------
238// GET /api/files/root-access?rootPath=<absolute-root-path>
239// Returns users that can access a configured root and their mode (R / R+W).
240// ---------------------------------------------------------------------------
241router.get('/root-access', requireAuth, (req, res) =>
242{
243 const rootPath = String(req.query.rootPath || '').trim();
244 if (!rootPath)
245 {
246 return res.status(400).json({ error: 'rootPath is required.' });
247 }
248
249 const config = loadConfig();
250 const roots = getEffectivePaths(config.paths || []);
251 const info = resolveRoot(rootPath, roots);
252 if (!info) return res.status(403).json({ error: 'Access denied.' });
253 if (!sameResolvedPath(rootPath, info.root))
254 {
255 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
256 }
257 if (!canRead(req.user, info.label))
258 {
259 return res.status(403).json({ error: 'Access denied.' });
260 }
261
262 const db = getDb();
263 const rows = db.prepare('SELECT username, is_admin, permissions FROM users').all();
264 const users = [];
265
266 for (const row of rows)
267 {
268 if (row.is_admin === 1)
269 {
270 users.push({ username: row.username, mode: 'R+W' });
271 continue;
272 }
273
274 let permissions = {};
275 try
276 {
277 permissions = JSON.parse(row.permissions || '{}');
278 } catch
279 {
280 permissions = {};
281 }
282
283 const perm = permissions[info.label];
284 if (!perm || typeof perm !== 'object') continue;
285 const canWriteRoot = !!perm.write;
286 const canReadRoot = !!perm.read || canWriteRoot;
287 if (!canReadRoot) continue;
288 users.push({ username: row.username, mode: canWriteRoot ? 'R+W' : 'R' });
289 }
290
291 users.sort((a, b) =>
292 {
293 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
294 const byMode = modeRank(a.mode) - modeRank(b.mode);
295 if (byMode !== 0) return byMode;
296 return String(a.username).localeCompare(String(b.username));
297 });
298
299 const rootAliases = rootAliasesFromConfig(config);
300 const alias = String(rootAliases[path.resolve(info.root)] || '').trim();
301 res.json({
302 root: {
303 path: info.root,
304 label: alias || info.label,
305 originalName: info.label,
306 alias: alias || null,
307 },
308 users,
309 });
310});
311
312// ---------------------------------------------------------------------------
313// POST /api/files/root-alias
314// Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
315// Sets a display-only alias for a configured root.
316// ---------------------------------------------------------------------------
317router.post('/root-alias', requireAuth, (req, res) =>
318{
319 const rootPath = String(req.body && req.body.rootPath || '').trim();
320 const alias = String(req.body && req.body.alias || '').trim();
321 if (!rootPath || !alias)
322 {
323 return res.status(400).json({ error: 'rootPath and alias are required.' });
324 }
325
326 const roots = effectivePaths();
327 const info = resolveRoot(rootPath, roots);
328 if (!info) return res.status(403).json({ error: 'Access denied.' });
329 if (!sameResolvedPath(rootPath, info.root))
330 {
331 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
332 }
333 if (!canWrite(req.user, info.label))
334 {
335 return res.status(403).json({ error: 'Access denied.' });
336 }
337
338 const config = loadConfig();
339 const rootAliases = rootAliasesFromConfig(config);
340 const key = path.resolve(info.root);
341 if (alias === info.label)
342 {
343 delete rootAliases[key];
344 } else
345 {
346 rootAliases[key] = alias;
347 }
348 config.rootAliases = rootAliases;
349 saveConfig(config);
350
351 res.json({
352 ok: true,
353 root: {
354 path: info.root,
355 label: alias,
356 originalName: info.label,
357 alias,
358 },
359 });
360});
361
362// ---------------------------------------------------------------------------
363// GET /api/files/list?dir=<absolute-path>
364// Lists files and folders in the given directory.
365// ---------------------------------------------------------------------------
366router.get('/list', requireAuth, (req, res) =>
367{
368 const dir = req.query.dir;
369 if (!dir) return res.status(400).json({ error: 'dir is required.' });
370
371 const roots = effectivePaths();
372 const info = resolveRoot(dir, roots);
373 if (!info) return res.status(403).json({ error: 'Access denied.' });
374 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
375
376 let entries;
377 try
378 {
379 entries = fs.readdirSync(dir, { withFileTypes: true });
380 } catch
381 {
382 return res.status(404).json({ error: 'Directory not found.' });
383 }
384
385 const items = entries.map(e =>
386 {
387 const fullPath = path.join(dir, e.name);
388 let size = null;
389 let mtime = null;
390 try
391 {
392 const stat = fs.statSync(fullPath);
393 size = stat.size;
394 mtime = stat.mtime.toISOString();
395 } catch { /* ignore */ }
396
397 return {
398 name: e.name,
399 isDir: e.isDirectory(),
400 size,
401 mtime,
402 path: fullPath,
403 };
404 });
405
406 res.json({ items });
407});
408
409// ---------------------------------------------------------------------------
410// GET /api/files/meta?file=<absolute-path>
411// Returns file metadata from the DB.
412// ---------------------------------------------------------------------------
413router.get('/meta', requireAuth, (req, res) =>
414{
415 const file = req.query.file;
416 if (!file) return res.status(400).json({ error: 'file is required.' });
417
418 const roots = effectivePaths();
419 const info = resolveRoot(file, roots);
420 if (!info || !canRead(req.user, info.label))
421 {
422 return res.status(403).json({ error: 'Access denied.' });
423 }
424
425 let stat;
426 try
427 {
428 stat = fs.statSync(file);
429 } catch
430 {
431 return res.status(404).json({ error: 'File not found.' });
432 }
433
434 const db = getDb();
435 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
436
437 res.json({
438 name: path.basename(file),
439 size: stat.size,
440 mtime: stat.mtime.toISOString(),
441 uploader: meta ? meta.uploader : '',
442 downloaders: meta ? JSON.parse(meta.downloaders) : [],
443 });
444});
445
446// ---------------------------------------------------------------------------
447// GET /api/files/space?dir=<absolute-path>
448// Returns recursive used bytes for dir and available bytes on its root fs.
449// ---------------------------------------------------------------------------
450router.get('/space', requireAuth, (req, res) =>
451{
452 const dir = req.query.dir;
453 if (!dir) return res.status(400).json({ error: 'dir is required.' });
454
455 const roots = effectivePaths();
456 const info = resolveRoot(dir, roots);
457 if (!info || !canRead(req.user, info.label))
458 {
459 return res.status(403).json({ error: 'Access denied.' });
460 }
461
462 if (!fs.existsSync(dir))
463 {
464 return res.status(404).json({ error: 'Path not found.' });
465 }
466
467 const usedBytes = getRecursiveSize(dir);
468 const freeBytes = getFreeBytes(info.root);
469 res.json({
470 usedBytes,
471 freeBytes,
472 rootPath: info.root,
473 rootLabel: info.label,
474 });
475});
476
477// ---------------------------------------------------------------------------
478// GET /api/files/download?file=<absolute-path>
479// Streams the file to the client; records the download.
480// ---------------------------------------------------------------------------
481router.get('/download', requireAuth, (req, res) =>
482{
483 const file = req.query.file;
484 if (!file) return res.status(400).json({ error: 'file is required.' });
485
486 const roots = effectivePaths();
487 const info = resolveRoot(file, roots);
488 if (!info || !canRead(req.user, info.label))
489 {
490 return res.status(403).json({ error: 'Access denied.' });
491 }
492
493 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
494 {
495 return res.status(404).json({ error: 'File not found.' });
496 }
497
498 // Record download
499 const db = getDb();
500 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
501 if (meta)
502 {
503 const downloaders = JSON.parse(meta.downloaders);
504 if (!downloaders.includes(req.user.username))
505 {
506 downloaders.push(req.user.username);
507 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
508 .run([JSON.stringify(downloaders), file]);
509 }
510 } else
511 {
512 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
513 .run([file, '', JSON.stringify([req.user.username])]);
514 }
515
516 res.download(file, path.basename(file));
517});
518
519// ---------------------------------------------------------------------------
520// GET /api/files/thumbnail?file=<absolute-path>
521// Returns a pre-generated cached thumbnail if present.
522// ---------------------------------------------------------------------------
523router.get('/thumbnail', requireAuth, async (req, res) =>
524{
525 const file = req.query.file;
526 if (!file) return res.status(400).json({ error: 'file is required.' });
527
528 const roots = effectivePaths();
529 const info = resolveRoot(file, roots);
530 if (!info || !canRead(req.user, info.label))
531 {
532 return res.status(403).json({ error: 'Access denied.' });
533 }
534
535 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
536 {
537 return res.status(404).json({ error: 'File not found.' });
538 }
539
540 const thumb = await getCachedThumbnailInfo(file);
541 if (!thumb)
542 {
543 return res.status(404).json({ error: 'Thumbnail not ready.' });
544 }
545
546 res.type(thumb.contentType);
547 res.set('Cache-Control', 'private, max-age=10');
548 res.sendFile(thumb.thumbPath);
549});
550
551// ---------------------------------------------------------------------------
552// POST /api/files/upload?dir=<absolute-path>
553// Accepts multipart file upload.
554// ---------------------------------------------------------------------------
555router.post('/upload', requireAuth, (req, res, next) =>
556{
557 const dir = req.query.dir;
558 if (!dir) return res.status(400).json({ error: 'dir is required.' });
559
560 const roots = effectivePaths();
561 const info = resolveRoot(dir, roots);
562 if (!info || !canWrite(req.user, info.label))
563 {
564 return res.status(403).json({ error: 'Access denied.' });
565 }
566
567 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
568 {
569 return res.status(404).json({ error: 'Directory not found.' });
570 }
571
572 const announcedSize = Number(req.header('x-upload-size') || 0);
573 if (Number.isFinite(announcedSize) && announcedSize > 0)
574 {
575 const freeBytes = getFreeBytes(info.root);
576 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
577 {
578 return res.status(413).json({
579 error: 'Upload too large for remaining free space on selected root.',
580 freeBytes,
581 requiredBytes: announcedSize,
582 });
583 }
584 }
585
586 req._uploadDir = dir;
587
588 upload.array('files')(req, res, (err) =>
589 {
590 if (err) return res.status(500).json({ error: err.message });
591
592 const db = getDb();
593 for (const f of (req.files || []))
594 {
595 const filePath = path.join(dir, f.originalname);
596 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
597 if (existing)
598 {
599 db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')
600 .run([req.user.username, filePath]);
601 } else
602 {
603 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
604 .run([filePath, req.user.username, '[]']);
605 }
606 }
607 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
608 });
609});
610
611// ---------------------------------------------------------------------------
612// POST /api/files/rename
613// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
614// ---------------------------------------------------------------------------
615router.post('/rename', requireAuth, (req, res) =>
616{
617 const { from, to } = req.body;
618 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
619
620 // Prevent path traversal in the new name
621 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
622 {
623 return res.status(400).json({ error: 'Invalid name.' });
624 }
625
626 const roots = effectivePaths();
627 const info = resolveRoot(from, roots);
628 if (!info || !canWrite(req.user, info.label))
629 {
630 return res.status(403).json({ error: 'Access denied.' });
631 }
632
633 const dest = path.join(path.dirname(from), to);
634
635 // Ensure dest is still inside the same root
636 if (!getAllowedRoot(dest, roots))
637 {
638 return res.status(403).json({ error: 'Access denied.' });
639 }
640
641 try
642 {
643 fs.renameSync(from, dest);
644 } catch (err)
645 {
646 return res.status(500).json({ error: err.message });
647 }
648
649 rewriteMetaPaths(from, dest);
650
651 res.json({ ok: true });
652});
653
654// ---------------------------------------------------------------------------
655// POST /api/files/move
656// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
657// ---------------------------------------------------------------------------
658router.post('/move', requireAuth, (req, res) =>
659{
660 const { from, toDir } = req.body;
661 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
662 const targetName = req.body && req.body.targetName != null
663 ? String(req.body.targetName).trim()
664 : '';
665 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
666 if (!['error', 'overwrite', 'rename'].includes(conflict))
667 {
668 return res.status(400).json({ error: 'Invalid conflict strategy.' });
669 }
670
671 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
672 {
673 return res.status(400).json({ error: 'Invalid targetName.' });
674 }
675
676 const roots = effectivePaths();
677 const fromInfo = resolveRoot(from, roots);
678 const toInfo = resolveRoot(toDir, roots);
679 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
680 if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))
681 {
682 return res.status(403).json({ error: 'Access denied.' });
683 }
684
685 let sourceStat;
686 let destStat;
687 try
688 {
689 sourceStat = fs.statSync(from);
690 destStat = fs.statSync(toDir);
691 } catch
692 {
693 return res.status(404).json({ error: 'Source or destination not found.' });
694 }
695
696 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
697
698 const requestedName = targetName || path.basename(from);
699 const requestedDest = path.join(toDir, requestedName);
700 if (!getAllowedRoot(requestedDest, roots)) return res.status(403).json({ error: 'Access denied.' });
701 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
702 {
703 return res.status(400).json({ error: 'Cannot move onto itself.' });
704 }
705 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
706 {
707 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
708 }
709
710 let dest = requestedDest;
711 let resolvedConflict = 'none';
712
713 if (fs.existsSync(requestedDest))
714 {
715 if (conflict === 'error')
716 {
717 return res.status(409).json({ error: 'Destination already exists.' });
718 }
719
720 if (conflict === 'rename')
721 {
722 dest = pickNumberedPath(toDir, requestedName);
723 resolvedConflict = 'rename';
724 }
725
726 if (conflict === 'overwrite')
727 {
728 try
729 {
730 removePathRecursive(requestedDest);
731 } catch (err)
732 {
733 return res.status(500).json({ error: err.message });
734 }
735 resolvedConflict = 'overwrite';
736 }
737 }
738
739 if (sameResolvedPath(from, dest))
740 {
741 return res.status(400).json({ error: 'Cannot move onto itself.' });
742 }
743
744 try
745 {
746 fs.renameSync(from, dest);
747 } catch (err)
748 {
749 return res.status(500).json({ error: err.message });
750 }
751
752 rewriteMetaPaths(from, dest);
753 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
754});
755
756// ---------------------------------------------------------------------------
757// POST /api/files/mkdir
758// Body: { dir: <absolute-path>, name: <folder-name> }
759// ---------------------------------------------------------------------------
760router.post('/mkdir', requireAuth, (req, res) =>
761{
762 const { dir, name } = req.body;
763 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
764
765 if (path.basename(name) !== name)
766 {
767 return res.status(400).json({ error: 'Invalid folder name.' });
768 }
769
770 const roots = effectivePaths();
771 const info = resolveRoot(dir, roots);
772 if (!info || !canWrite(req.user, info.label))
773 {
774 return res.status(403).json({ error: 'Access denied.' });
775 }
776
777 const newDir = path.join(dir, name);
778 if (!getAllowedRoot(newDir, roots))
779 {
780 return res.status(403).json({ error: 'Access denied.' });
781 }
782
783 try
784 {
785 fs.mkdirSync(newDir, { recursive: false });
786 } catch (err)
787 {
788 return res.status(500).json({ error: err.message });
789 }
790
791 res.json({ ok: true, path: newDir });
792});
793
794// ---------------------------------------------------------------------------
795// POST /api/files/delete
796// Body: { path: <absolute-path> }
797// ---------------------------------------------------------------------------
798router.post('/delete', requireAuth, (req, res) =>
799{
800 const target = req.body.path;
801 if (!target) return res.status(400).json({ error: 'path is required.' });
802
803 const roots = effectivePaths();
804 const info = resolveRoot(target, roots);
805 if (!info || !canWrite(req.user, info.label))
806 {
807 return res.status(403).json({ error: 'Access denied.' });
808 }
809
810 // Do not allow deleting a configured root itself
811 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
812 {
813 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
814 }
815
816 try
817 {
818 const stat = fs.statSync(target);
819 if (stat.isDirectory())
820 {
821 fs.rmSync(target, { recursive: true, force: true });
822 } else
823 {
824 fs.unlinkSync(target);
825 }
826 } catch (err)
827 {
828 return res.status(500).json({ error: err.message });
829 }
830
831 // Clean up any DB meta entries under that path
832 const db = getDb();
833 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
834 .run([target, target + path.sep + '%']);
835
836 res.json({ ok: true });
837});
838
839// ---------------------------------------------------------------------------
840// GET /api/files/folder-images?dir=<absolute-path>
841// Returns images inside dir (recursive) that already have a cached thumbnail.
842// Only images with a ready thumbnail are included (user constraint).
843// ---------------------------------------------------------------------------
844router.get('/folder-images', requireAuth, async (req, res) =>
845{
846 const dir = String(req.query.dir || '').trim();
847 if (!dir) return res.status(400).json({ error: 'dir is required.' });
848
849 const roots = effectivePaths();
850 const info = resolveRoot(dir, roots);
851 if (!info || !canRead(req.user, info.label))
852 {
853 return res.status(403).json({ error: 'Access denied.' });
854 }
855
856 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
857 {
858 return res.status(404).json({ error: 'Directory not found.' });
859 }
860
861 const images = await getImagesWithThumbnailsInDir(dir);
862 // Filter out any that escaped to a different root (safety check).
863 const filtered = images.filter(({ filePath }) => !!getAllowedRoot(filePath, roots));
864
865 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
866});
867
868// ---------------------------------------------------------------------------
869// GET /api/files/folder-icon?dir=<absolute-path>
870// Returns the current icon source file for a folder (explicit or auto-first).
871// ---------------------------------------------------------------------------
872router.get('/folder-icon', requireAuth, async (req, res) =>
873{
874 const dir = String(req.query.dir || '').trim();
875 if (!dir) return res.status(400).json({ error: 'dir is required.' });
876
877 const roots = effectivePaths();
878 const info = resolveRoot(dir, roots);
879 if (!info || !canRead(req.user, info.label))
880 {
881 return res.status(403).json({ error: 'Access denied.' });
882 }
883
884 const sourceFile = await getFolderIconSourceFile(dir);
885 if (!sourceFile) return res.json({ icon: null });
886
887 // Verify the source is still accessible within a configured root.
888 if (!getAllowedRoot(sourceFile, roots)) return res.json({ icon: null });
889
890 res.json({ icon: { filePath: sourceFile } });
891});
892
893// ---------------------------------------------------------------------------
894// POST /api/files/folder-icon
895// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
896// Requires write access; the image must already have a cached thumbnail.
897// ---------------------------------------------------------------------------
898router.post('/folder-icon', requireAuth, async (req, res) =>
899{
900 const folderPath = String((req.body && req.body.folderPath) || '').trim();
901 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
902
903 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
904
905 const roots = effectivePaths();
906 const info = resolveRoot(folderPath, roots);
907 if (!info || !canWrite(req.user, info.label))
908 {
909 return res.status(403).json({ error: 'Access denied.' });
910 }
911
912 let stat;
913 try { stat = fs.statSync(folderPath); }
914 catch { return res.status(404).json({ error: 'Folder not found.' }); }
915 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
916
917 if (rawImage !== null)
918 {
919 // Verify the image is inside a readable root.
920 const imageRoot = getAllowedRoot(rawImage, roots);
921 if (!imageRoot) return res.status(403).json({ error: 'Image not accessible.' });
922
923 // Must already have a cached thumbnail — only thumbnailed images can be selected.
924 const thumb = await getCachedThumbnailInfo(rawImage);
925 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
926 }
927
928 await setFolderIconAssignment(folderPath, rawImage);
929 res.json({ ok: true });
930});
931
932module.exports = router;