BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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