BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

save volume setting
timfa Tim Falken · pushed by timfa · 6 months ago
0a9d5f29 History
files.js 35.6 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, watched_by 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, watched_by)
263 VALUES (?, ?, ?, ?)
264 ON CONFLICT(file_path) DO UPDATE SET
265 uploader = excluded.uploader,
266 downloaders = excluded.downloaders,
267 watched_by = excluded.watched_by
268 `);
269
270 for (const row of rows)
271 {
272 const nextPath = row.file_path === fromPath
273 ? toPath
274 : toPath + row.file_path.slice(fromPath.length);
275 del.run([row.file_path]);
276 upsert.run([nextPath, row.uploader, row.downloaders, row.watched_by || '{}']);
277 }
278}
279
280function parseJsonArray (raw)
281{
282 try
283 {
284 const value = JSON.parse(raw || '[]');
285 return Array.isArray(value) ? value : [];
286 } catch
287 {
288 return [];
289 }
290}
291
292function parseJsonObject (raw)
293{
294 try
295 {
296 const value = JSON.parse(raw || '{}');
297 if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
298 return value;
299 } catch
300 {
301 return {};
302 }
303}
304
305function watchStatusForProgress (progress)
306{
307 if (!Number.isFinite(progress) || progress < 0) return null;
308 if (progress >= 0.7) return 'fully';
309 if (progress >= 0.3) return 'partway';
310 return null;
311}
312
313function splitNameExt (name)
314{
315 const dot = String(name || '').lastIndexOf('.');
316 if (dot <= 0) return { stem: String(name || ''), ext: '' };
317 return {
318 stem: String(name).slice(0, dot),
319 ext: String(name).slice(dot),
320 };
321}
322
323function pickNumberedPath (dir, requestedName)
324{
325 const parsed = splitNameExt(requestedName);
326 const stem = parsed.stem || 'file';
327 const ext = parsed.ext || '';
328 let index = 1;
329
330 while (index <= 10000)
331 {
332 const candidateName = `${stem} (${index})${ext}`;
333 const candidatePath = path.join(dir, candidateName);
334 if (!fs.existsSync(candidatePath)) return candidatePath;
335 index++;
336 }
337
338 throw new Error('Could not generate a free destination name.');
339}
340
341function removePathRecursive (targetPath)
342{
343 const stat = fs.lstatSync(targetPath);
344 if (stat.isDirectory())
345 {
346 fs.rmSync(targetPath, { recursive: true, force: true });
347 } else
348 {
349 fs.unlinkSync(targetPath);
350 }
351}
352
353// ---------------------------------------------------------------------------
354// GET /api/files/roots
355// Returns the effective configured paths the user can read.
356// ---------------------------------------------------------------------------
357router.get('/roots', requireAuth, (req, res) =>
358{
359 const config = loadConfig();
360 const roots = getEffectivePaths(config.paths || []);
361 const rootAliases = rootAliasesFromConfig(config);
362
363 const readable = roots
364 .filter(r => canRead(req.user, path.basename(r)))
365 .map(r =>
366 {
367 const originalName = path.basename(r);
368 const alias = String(rootAliases[path.resolve(r)] || '').trim();
369 return {
370 label: alias || originalName,
371 path: r,
372 originalName,
373 alias: alias || null,
374 };
375 });
376 res.json({ roots: readable });
377});
378
379// ---------------------------------------------------------------------------
380// GET /api/files/root-access?rootPath=<absolute-root-path>
381// Returns users that can access a configured root and their mode (R / R+W).
382// ---------------------------------------------------------------------------
383router.get('/root-access', requireAuth, (req, res) =>
384{
385 const rootPath = String(req.query.rootPath || '').trim();
386 if (!rootPath)
387 {
388 return res.status(400).json({ error: 'rootPath is required.' });
389 }
390
391 const config = loadConfig();
392 const roots = getEffectivePaths(config.paths || []);
393 const info = resolveRoot(rootPath, roots);
394 if (!info) return res.status(403).json({ error: 'Access denied.' });
395 if (!sameResolvedPath(rootPath, info.root))
396 {
397 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
398 }
399 if (!canRead(req.user, info.label))
400 {
401 return res.status(403).json({ error: 'Access denied.' });
402 }
403
404 const db = getDb();
405 const rows = db.prepare('SELECT username, is_admin, permissions FROM users').all();
406 const users = [];
407
408 for (const row of rows)
409 {
410 if (row.is_admin === 1)
411 {
412 users.push({ username: row.username, mode: 'R+W' });
413 continue;
414 }
415
416 let permissions = {};
417 try
418 {
419 permissions = JSON.parse(row.permissions || '{}');
420 } catch
421 {
422 permissions = {};
423 }
424
425 const perm = permissions[info.label];
426 if (!perm || typeof perm !== 'object') continue;
427 const canWriteRoot = !!perm.write;
428 const canReadRoot = !!perm.read || canWriteRoot;
429 if (!canReadRoot) continue;
430 users.push({ username: row.username, mode: canWriteRoot ? 'R+W' : 'R' });
431 }
432
433 users.sort((a, b) =>
434 {
435 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
436 const byMode = modeRank(a.mode) - modeRank(b.mode);
437 if (byMode !== 0) return byMode;
438 return String(a.username).localeCompare(String(b.username));
439 });
440
441 const rootAliases = rootAliasesFromConfig(config);
442 const alias = String(rootAliases[path.resolve(info.root)] || '').trim();
443 res.json({
444 root: {
445 path: info.root,
446 label: alias || info.label,
447 originalName: info.label,
448 alias: alias || null,
449 },
450 users,
451 });
452});
453
454// ---------------------------------------------------------------------------
455// POST /api/files/root-alias
456// Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
457// Sets a display-only alias for a configured root.
458// ---------------------------------------------------------------------------
459router.post('/root-alias', requireAuth, (req, res) =>
460{
461 const rootPath = String(req.body && req.body.rootPath || '').trim();
462 const alias = String(req.body && req.body.alias || '').trim();
463 if (!rootPath || !alias)
464 {
465 return res.status(400).json({ error: 'rootPath and alias are required.' });
466 }
467
468 const roots = effectivePaths();
469 const info = resolveRoot(rootPath, roots);
470 if (!info) return res.status(403).json({ error: 'Access denied.' });
471 if (!sameResolvedPath(rootPath, info.root))
472 {
473 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
474 }
475 if (!canWrite(req.user, info.label))
476 {
477 return res.status(403).json({ error: 'Access denied.' });
478 }
479
480 const config = loadConfig();
481 const rootAliases = rootAliasesFromConfig(config);
482 const key = path.resolve(info.root);
483 if (alias === info.label)
484 {
485 delete rootAliases[key];
486 } else
487 {
488 rootAliases[key] = alias;
489 }
490 config.rootAliases = rootAliases;
491 saveConfig(config);
492
493 res.json({
494 ok: true,
495 root: {
496 path: info.root,
497 label: alias,
498 originalName: info.label,
499 alias,
500 },
501 });
502});
503
504// ---------------------------------------------------------------------------
505// GET /api/files/list?dir=<absolute-path>
506// Lists files and folders in the given directory.
507// ---------------------------------------------------------------------------
508router.get('/list', requireAuth, (req, res) =>
509{
510 const dir = req.query.dir;
511 if (!dir) return res.status(400).json({ error: 'dir is required.' });
512
513 const roots = effectivePaths();
514 const info = resolveRoot(dir, roots);
515 if (!info) return res.status(403).json({ error: 'Access denied.' });
516 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
517
518 let entries;
519 try
520 {
521 entries = fs.readdirSync(dir, { withFileTypes: true });
522 } catch
523 {
524 return res.status(404).json({ error: 'Directory not found.' });
525 }
526
527 const items = entries.map(e =>
528 {
529 const fullPath = path.join(dir, e.name);
530 let size = null;
531 let mtime = null;
532 try
533 {
534 const stat = fs.statSync(fullPath);
535 size = stat.size;
536 mtime = stat.mtime.toISOString();
537 } catch { /* ignore */ }
538
539 return {
540 name: e.name,
541 isDir: e.isDirectory(),
542 size,
543 mtime,
544 path: fullPath,
545 };
546 });
547
548 res.json({ items });
549});
550
551// ---------------------------------------------------------------------------
552// GET /api/files/meta?file=<absolute-path>
553// Returns file metadata from the DB.
554// ---------------------------------------------------------------------------
555router.get('/meta', requireAuth, (req, res) =>
556{
557 const file = req.query.file;
558 if (!file) return res.status(400).json({ error: 'file is required.' });
559
560 const roots = effectivePaths();
561 const info = resolveRoot(file, roots);
562 if (!info || !canRead(req.user, info.label))
563 {
564 return res.status(403).json({ error: 'Access denied.' });
565 }
566
567 let stat;
568 try
569 {
570 stat = fs.statSync(file);
571 } catch
572 {
573 return res.status(404).json({ error: 'File not found.' });
574 }
575
576 const db = getDb();
577 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
578
579 res.json({
580 name: path.basename(file),
581 size: stat.size,
582 mtime: stat.mtime.toISOString(),
583 uploader: meta ? meta.uploader : '',
584 downloaders: meta ? parseJsonArray(meta.downloaders) : [],
585 watchedBy: meta ? parseJsonObject(meta.watched_by) : {},
586 });
587});
588
589// ---------------------------------------------------------------------------
590// GET /api/files/space?dir=<absolute-path>
591// Returns recursive used bytes for dir and available bytes on its root fs.
592// ---------------------------------------------------------------------------
593router.get('/space', requireAuth, (req, res) =>
594{
595 const dir = req.query.dir;
596 if (!dir) return res.status(400).json({ error: 'dir is required.' });
597
598 const roots = effectivePaths();
599 const info = resolveRoot(dir, roots);
600 if (!info || !canRead(req.user, info.label))
601 {
602 return res.status(403).json({ error: 'Access denied.' });
603 }
604
605 if (!fs.existsSync(dir))
606 {
607 return res.status(404).json({ error: 'Path not found.' });
608 }
609
610 const usedBytes = getRecursiveSize(dir);
611 const freeBytes = getFreeBytes(info.root);
612 res.json({
613 usedBytes,
614 freeBytes,
615 rootPath: info.root,
616 rootLabel: info.label,
617 });
618});
619
620// ---------------------------------------------------------------------------
621// GET /api/files/download?file=<absolute-path>
622// Streams the file to the client; records the download.
623// ---------------------------------------------------------------------------
624router.get('/download', requireAuth, (req, res) =>
625{
626 const file = req.query.file;
627 if (!file) return res.status(400).json({ error: 'file is required.' });
628
629 const roots = effectivePaths();
630 const info = resolveRoot(file, roots);
631 if (!info || !canRead(req.user, info.label))
632 {
633 return res.status(403).json({ error: 'Access denied.' });
634 }
635
636 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
637 {
638 return res.status(404).json({ error: 'File not found.' });
639 }
640
641 // Record download
642 const db = getDb();
643 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
644 if (meta)
645 {
646 const downloaders = parseJsonArray(meta.downloaders);
647 if (!downloaders.includes(req.user.username))
648 {
649 downloaders.push(req.user.username);
650 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
651 .run([JSON.stringify(downloaders), file]);
652 }
653 } else
654 {
655 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
656 .run([file, '', JSON.stringify([req.user.username]), '{}']);
657 }
658
659 res.download(file, path.basename(file));
660});
661
662// ---------------------------------------------------------------------------
663// POST /api/files/watch-progress
664// Body: { filePath: <absolute-path>, progress: <0..1> }
665// Records per-user video watch state for sidebar display.
666// ---------------------------------------------------------------------------
667router.post('/watch-progress', requireAuth, (req, res) =>
668{
669 const filePath = String(req.body && req.body.filePath || '').trim();
670 const progress = Number(req.body && req.body.progress);
671 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
672
673 const status = watchStatusForProgress(progress);
674 if (!status)
675 {
676 return res.json({ ok: true, updated: false });
677 }
678
679 const roots = effectivePaths();
680 const info = resolveRoot(filePath, roots);
681 if (!info || !canRead(req.user, info.label))
682 {
683 return res.status(403).json({ error: 'Access denied.' });
684 }
685
686 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
687 {
688 return res.status(404).json({ error: 'File not found.' });
689 }
690
691 const db = getDb();
692 const row = db.prepare('SELECT uploader, downloaders, watched_by FROM file_meta WHERE file_path = ?').get([filePath]);
693 const watchedBy = parseJsonObject(row && row.watched_by);
694 const prev = String(watchedBy[req.user.username] || '').toLowerCase();
695 const next = prev === 'fully' ? 'fully' : status;
696 if (prev === next)
697 {
698 return res.json({ ok: true, updated: false, status: next });
699 }
700
701 watchedBy[req.user.username] = next;
702 if (row)
703 {
704 db.prepare('UPDATE file_meta SET watched_by = ? WHERE file_path = ?')
705 .run([JSON.stringify(watchedBy), filePath]);
706 } else
707 {
708 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
709 .run([filePath, '', '[]', JSON.stringify(watchedBy)]);
710 }
711
712 res.json({ ok: true, updated: true, status: next });
713});
714
715// ---------------------------------------------------------------------------
716// POST /api/files/video-stream
717// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
718// ---------------------------------------------------------------------------
719router.post('/video-stream', requireAuth, async (req, res, next) =>
720{
721 try
722 {
723 const filePath = String(req.body?.filePath || '').trim();
724 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
725
726 const roots = effectivePaths();
727 const info = resolveRoot(filePath, 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(filePath) || fs.statSync(filePath).isDirectory())
734 {
735 return res.status(404).json({ error: 'File not found.' });
736 }
737
738 const session = await createVideoStreamSession(filePath);
739 res.json({
740 sessionId: session.sessionId,
741 playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
742 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
743 subtitleTracks: session.subtitleTracks.map((track) => ({
744 label: track.label,
745 language: track.language,
746 default: !!track.isDefault,
747 src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`,
748 })),
749 });
750 } catch (err)
751 {
752 next(err);
753 }
754});
755
756// ---------------------------------------------------------------------------
757// GET /api/files/video-stream/:sessionId/:assetPath(*)
758// Streams HLS assets for a previously created short-lived video session.
759// ---------------------------------------------------------------------------
760router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>
761{
762 try
763 {
764 await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, res);
765 } catch (err)
766 {
767 next(err);
768 }
769});
770
771// ---------------------------------------------------------------------------
772// GET /api/files/download-zip?dir=<absolute-path>
773// Authenticated. Streams a zip of the given directory.
774// ---------------------------------------------------------------------------
775router.get('/download-zip', requireAuth, async (req, res) =>
776{
777 const dir = req.query.dir;
778 if (!dir) return res.status(400).json({ error: 'dir is required.' });
779
780 const roots = effectivePaths();
781 const info = resolveRoot(dir, roots);
782 if (!info || !canRead(req.user, info.label))
783 {
784 return res.status(403).json({ error: 'Access denied.' });
785 }
786
787 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
788 {
789 return res.status(404).json({ error: 'Directory not found.' });
790 }
791
792 // Use a hash of the dir path as cache key so concurrent users share the cache.
793 const cacheKey = crypto.createHash('sha256').update(dir).digest('hex');
794 try
795 {
796 const zipPath = await buildZip(dir, cacheKey);
797 const zipName = `${path.basename(dir)}.zip`;
798 res.download(zipPath, zipName);
799 } catch (err)
800 {
801 res.status(500).json({ error: 'Failed to create zip archive.' });
802 }
803});
804
805// ---------------------------------------------------------------------------
806// GET /api/files/thumbnail?file=<absolute-path>
807// Returns a pre-generated cached thumbnail if present.
808// ---------------------------------------------------------------------------
809router.get('/thumbnail', requireAuth, async (req, res) =>
810{
811 const file = req.query.file;
812 if (!file) return res.status(400).json({ error: 'file is required.' });
813
814 const roots = effectivePaths();
815 const info = resolveRoot(file, roots);
816 if (!info || !canRead(req.user, info.label))
817 {
818 return res.status(403).json({ error: 'Access denied.' });
819 }
820
821 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
822 {
823 return res.status(404).json({ error: 'File not found.' });
824 }
825
826 const thumb = await getCachedThumbnailInfo(file);
827 if (!thumb)
828 {
829 return res.status(404).json({ error: 'Thumbnail not ready.' });
830 }
831
832 res.type(thumb.contentType);
833 res.set('Cache-Control', 'private, max-age=10');
834 res.sendFile(thumb.thumbPath);
835});
836
837// ---------------------------------------------------------------------------
838// POST /api/files/upload?dir=<absolute-path>
839// Accepts multipart file upload.
840// ---------------------------------------------------------------------------
841router.post('/upload', requireAuth, (req, res, next) =>
842{
843 const dir = req.query.dir;
844 if (!dir) return res.status(400).json({ error: 'dir is required.' });
845
846 const roots = effectivePaths();
847 const info = resolveRoot(dir, roots);
848 if (!info || !canWrite(req.user, info.label))
849 {
850 return res.status(403).json({ error: 'Access denied.' });
851 }
852
853 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
854 {
855 return res.status(404).json({ error: 'Directory not found.' });
856 }
857
858 const announcedSize = Number(req.header('x-upload-size') || 0);
859 if (Number.isFinite(announcedSize) && announcedSize > 0)
860 {
861 const freeBytes = getFreeBytes(info.root);
862 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
863 {
864 return res.status(413).json({
865 error: 'Upload too large for remaining free space on selected root.',
866 freeBytes,
867 requiredBytes: announcedSize,
868 });
869 }
870 }
871
872 req._uploadDir = dir;
873
874 upload.array('files')(req, res, (err) =>
875 {
876 if (err) return res.status(500).json({ error: err.message });
877
878 const db = getDb();
879 for (const f of (req.files || []))
880 {
881 const filePath = path.join(dir, f.originalname);
882 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
883 if (existing)
884 {
885 db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')
886 .run([req.user.username, filePath]);
887 } else
888 {
889 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
890 .run([filePath, req.user.username, '[]']);
891 }
892 }
893 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
894 });
895});
896
897// ---------------------------------------------------------------------------
898// POST /api/files/rename
899// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
900// ---------------------------------------------------------------------------
901router.post('/rename', requireAuth, (req, res) =>
902{
903 const { from, to } = req.body;
904 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
905
906 // Prevent path traversal in the new name
907 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
908 {
909 return res.status(400).json({ error: 'Invalid name.' });
910 }
911
912 const roots = effectivePaths();
913 const info = resolveRoot(from, roots);
914 if (!info || !canWrite(req.user, info.label))
915 {
916 return res.status(403).json({ error: 'Access denied.' });
917 }
918
919 const dest = path.join(path.dirname(from), to);
920
921 // Ensure dest is still inside the same root
922 if (!getAllowedRoot(dest, roots))
923 {
924 return res.status(403).json({ error: 'Access denied.' });
925 }
926
927 try
928 {
929 fs.renameSync(from, dest);
930 } catch (err)
931 {
932 return res.status(500).json({ error: err.message });
933 }
934
935 rewriteMetaPaths(from, dest);
936
937 res.json({ ok: true });
938});
939
940// ---------------------------------------------------------------------------
941// POST /api/files/move
942// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
943// ---------------------------------------------------------------------------
944router.post('/move', requireAuth, (req, res) =>
945{
946 const { from, toDir } = req.body;
947 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
948 const targetName = req.body && req.body.targetName != null
949 ? String(req.body.targetName).trim()
950 : '';
951 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
952 if (!['error', 'overwrite', 'rename'].includes(conflict))
953 {
954 return res.status(400).json({ error: 'Invalid conflict strategy.' });
955 }
956
957 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
958 {
959 return res.status(400).json({ error: 'Invalid targetName.' });
960 }
961
962 const roots = effectivePaths();
963 const fromInfo = resolveRoot(from, roots);
964 const toInfo = resolveRoot(toDir, roots);
965 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
966 if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))
967 {
968 return res.status(403).json({ error: 'Access denied.' });
969 }
970
971 let sourceStat;
972 let destStat;
973 try
974 {
975 sourceStat = fs.statSync(from);
976 destStat = fs.statSync(toDir);
977 } catch
978 {
979 return res.status(404).json({ error: 'Source or destination not found.' });
980 }
981
982 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
983
984 const requestedName = targetName || path.basename(from);
985 const requestedDest = path.join(toDir, requestedName);
986 if (!getAllowedRoot(requestedDest, roots)) return res.status(403).json({ error: 'Access denied.' });
987 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
988 {
989 return res.status(400).json({ error: 'Cannot move onto itself.' });
990 }
991 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
992 {
993 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
994 }
995
996 let dest = requestedDest;
997 let resolvedConflict = 'none';
998
999 if (fs.existsSync(requestedDest))
1000 {
1001 if (conflict === 'error')
1002 {
1003 return res.status(409).json({ error: 'Destination already exists.' });
1004 }
1005
1006 if (conflict === 'rename')
1007 {
1008 dest = pickNumberedPath(toDir, requestedName);
1009 resolvedConflict = 'rename';
1010 }
1011
1012 if (conflict === 'overwrite')
1013 {
1014 try
1015 {
1016 removePathRecursive(requestedDest);
1017 } catch (err)
1018 {
1019 return res.status(500).json({ error: err.message });
1020 }
1021 resolvedConflict = 'overwrite';
1022 }
1023 }
1024
1025 if (sameResolvedPath(from, dest))
1026 {
1027 return res.status(400).json({ error: 'Cannot move onto itself.' });
1028 }
1029
1030 try
1031 {
1032 fs.renameSync(from, dest);
1033 } catch (err)
1034 {
1035 return res.status(500).json({ error: err.message });
1036 }
1037
1038 rewriteMetaPaths(from, dest);
1039 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1040});
1041
1042// ---------------------------------------------------------------------------
1043// POST /api/files/mkdir
1044// Body: { dir: <absolute-path>, name: <folder-name> }
1045// ---------------------------------------------------------------------------
1046router.post('/mkdir', requireAuth, (req, res) =>
1047{
1048 const { dir, name } = req.body;
1049 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
1050
1051 if (path.basename(name) !== name)
1052 {
1053 return res.status(400).json({ error: 'Invalid folder name.' });
1054 }
1055
1056 const roots = effectivePaths();
1057 const info = resolveRoot(dir, roots);
1058 if (!info || !canWrite(req.user, info.label))
1059 {
1060 return res.status(403).json({ error: 'Access denied.' });
1061 }
1062
1063 const newDir = path.join(dir, name);
1064 if (!getAllowedRoot(newDir, roots))
1065 {
1066 return res.status(403).json({ error: 'Access denied.' });
1067 }
1068
1069 try
1070 {
1071 fs.mkdirSync(newDir, { recursive: false });
1072 } catch (err)
1073 {
1074 return res.status(500).json({ error: err.message });
1075 }
1076
1077 res.json({ ok: true, path: newDir });
1078});
1079
1080// ---------------------------------------------------------------------------
1081// POST /api/files/delete
1082// Body: { path: <absolute-path> }
1083// ---------------------------------------------------------------------------
1084router.post('/delete', requireAuth, (req, res) =>
1085{
1086 const target = req.body.path;
1087 if (!target) return res.status(400).json({ error: 'path is required.' });
1088
1089 const roots = effectivePaths();
1090 const info = resolveRoot(target, roots);
1091 if (!info || !canWrite(req.user, info.label))
1092 {
1093 return res.status(403).json({ error: 'Access denied.' });
1094 }
1095
1096 // Do not allow deleting a configured root itself
1097 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
1098 {
1099 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
1100 }
1101
1102 try
1103 {
1104 const stat = fs.statSync(target);
1105 if (stat.isDirectory())
1106 {
1107 fs.rmSync(target, { recursive: true, force: true });
1108 } else
1109 {
1110 fs.unlinkSync(target);
1111 }
1112 } catch (err)
1113 {
1114 return res.status(500).json({ error: err.message });
1115 }
1116
1117 // Clean up any DB meta entries under that path
1118 const db = getDb();
1119 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
1120 .run([target, target + path.sep + '%']);
1121
1122 res.json({ ok: true });
1123});
1124
1125// ---------------------------------------------------------------------------
1126// GET /api/files/folder-images?dir=<absolute-path>
1127// Returns images inside dir (recursive) that already have a cached thumbnail.
1128// Only images with a ready thumbnail are included (user constraint).
1129// ---------------------------------------------------------------------------
1130router.get('/folder-images', requireAuth, async (req, res) =>
1131{
1132 const dir = String(req.query.dir || '').trim();
1133 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1134
1135 const roots = effectivePaths();
1136 const info = resolveRoot(dir, roots);
1137 if (!info || !canRead(req.user, info.label))
1138 {
1139 return res.status(403).json({ error: 'Access denied.' });
1140 }
1141
1142 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1143 {
1144 return res.status(404).json({ error: 'Directory not found.' });
1145 }
1146
1147 const images = await getImagesWithThumbnailsInDir(dir);
1148 // Filter out any that escaped to a different root (safety check).
1149 const filtered = images.filter(({ filePath }) => !!getAllowedRoot(filePath, roots));
1150
1151 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1152});
1153
1154// ---------------------------------------------------------------------------
1155// GET /api/files/folder-icon?dir=<absolute-path>
1156// Returns the current icon source file for a folder (explicit or auto-first).
1157// ---------------------------------------------------------------------------
1158router.get('/folder-icon', requireAuth, async (req, res) =>
1159{
1160 const dir = String(req.query.dir || '').trim();
1161 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1162
1163 const roots = effectivePaths();
1164 const info = resolveRoot(dir, roots);
1165 if (!info || !canRead(req.user, info.label))
1166 {
1167 return res.status(403).json({ error: 'Access denied.' });
1168 }
1169
1170 const sourceFile = await getFolderIconSourceFile(dir);
1171 if (!sourceFile) return res.json({ icon: null });
1172
1173 // Verify the source is still accessible within a configured root.
1174 if (!getAllowedRoot(sourceFile, roots)) return res.json({ icon: null });
1175
1176 res.json({ icon: { filePath: sourceFile } });
1177});
1178
1179// ---------------------------------------------------------------------------
1180// POST /api/files/folder-icon
1181// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
1182// Requires write access; the image must already have a cached thumbnail.
1183// ---------------------------------------------------------------------------
1184router.post('/folder-icon', requireAuth, async (req, res) =>
1185{
1186 const folderPath = String((req.body && req.body.folderPath) || '').trim();
1187 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
1188
1189 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1190
1191 const roots = effectivePaths();
1192 const info = resolveRoot(folderPath, roots);
1193 if (!info || !canWrite(req.user, info.label))
1194 {
1195 return res.status(403).json({ error: 'Access denied.' });
1196 }
1197
1198 let stat;
1199 try { stat = fs.statSync(folderPath); }
1200 catch { return res.status(404).json({ error: 'Folder not found.' }); }
1201 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
1202
1203 if (rawImage !== null)
1204 {
1205 // Verify the image is inside a readable root.
1206 const imageRoot = getAllowedRoot(rawImage, roots);
1207 if (!imageRoot) return res.status(403).json({ error: 'Image not accessible.' });
1208
1209 // Must already have a cached thumbnail — only thumbnailed images can be selected.
1210 const thumb = await getCachedThumbnailInfo(rawImage);
1211 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
1212 }
1213
1214 await setFolderIconAssignment(folderPath, rawImage);
1215 res.json({ ok: true });
1216});
1217
1218module.exports = router;