BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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