BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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