BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

fix jumping partially
timfa Tim Falken · pushed by timfa · 6 months ago
ec1bfab7 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 durationSeconds: session.durationSeconds || null,
743 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
744 subtitleTracks: session.subtitleTracks.map((track) => ({
745 label: track.label,
746 language: track.language,
747 default: !!track.isDefault,
748 src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`,
749 })),
750 });
751 } catch (err)
752 {
753 next(err);
754 }
755});
756
757// ---------------------------------------------------------------------------
758// GET /api/files/video-stream/:sessionId/:assetPath(*)
759// Streams HLS assets for a previously created short-lived video session.
760// ---------------------------------------------------------------------------
761router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>
762{
763 try
764 {
765 await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, res);
766 } catch (err)
767 {
768 next(err);
769 }
770});
771
772// ---------------------------------------------------------------------------
773// GET /api/files/download-zip?dir=<absolute-path>
774// Authenticated. Streams a zip of the given directory.
775// ---------------------------------------------------------------------------
776router.get('/download-zip', requireAuth, async (req, res) =>
777{
778 const dir = req.query.dir;
779 if (!dir) return res.status(400).json({ error: 'dir is required.' });
780
781 const roots = effectivePaths();
782 const info = resolveRoot(dir, roots);
783 if (!info || !canRead(req.user, info.label))
784 {
785 return res.status(403).json({ error: 'Access denied.' });
786 }
787
788 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
789 {
790 return res.status(404).json({ error: 'Directory not found.' });
791 }
792
793 // Use a hash of the dir path as cache key so concurrent users share the cache.
794 const cacheKey = crypto.createHash('sha256').update(dir).digest('hex');
795 try
796 {
797 const zipPath = await buildZip(dir, cacheKey);
798 const zipName = `${path.basename(dir)}.zip`;
799 res.download(zipPath, zipName);
800 } catch (err)
801 {
802 res.status(500).json({ error: 'Failed to create zip archive.' });
803 }
804});
805
806// ---------------------------------------------------------------------------
807// GET /api/files/thumbnail?file=<absolute-path>
808// Returns a pre-generated cached thumbnail if present.
809// ---------------------------------------------------------------------------
810router.get('/thumbnail', requireAuth, async (req, res) =>
811{
812 const file = req.query.file;
813 if (!file) return res.status(400).json({ error: 'file is required.' });
814
815 const roots = effectivePaths();
816 const info = resolveRoot(file, roots);
817 if (!info || !canRead(req.user, info.label))
818 {
819 return res.status(403).json({ error: 'Access denied.' });
820 }
821
822 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
823 {
824 return res.status(404).json({ error: 'File not found.' });
825 }
826
827 const thumb = await getCachedThumbnailInfo(file);
828 if (!thumb)
829 {
830 return res.status(404).json({ error: 'Thumbnail not ready.' });
831 }
832
833 res.type(thumb.contentType);
834 res.set('Cache-Control', 'private, max-age=10');
835 res.sendFile(thumb.thumbPath);
836});
837
838// ---------------------------------------------------------------------------
839// POST /api/files/upload?dir=<absolute-path>
840// Accepts multipart file upload.
841// ---------------------------------------------------------------------------
842router.post('/upload', requireAuth, (req, res, next) =>
843{
844 const dir = req.query.dir;
845 if (!dir) return res.status(400).json({ error: 'dir is required.' });
846
847 const roots = effectivePaths();
848 const info = resolveRoot(dir, roots);
849 if (!info || !canWrite(req.user, info.label))
850 {
851 return res.status(403).json({ error: 'Access denied.' });
852 }
853
854 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
855 {
856 return res.status(404).json({ error: 'Directory not found.' });
857 }
858
859 const announcedSize = Number(req.header('x-upload-size') || 0);
860 if (Number.isFinite(announcedSize) && announcedSize > 0)
861 {
862 const freeBytes = getFreeBytes(info.root);
863 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
864 {
865 return res.status(413).json({
866 error: 'Upload too large for remaining free space on selected root.',
867 freeBytes,
868 requiredBytes: announcedSize,
869 });
870 }
871 }
872
873 req._uploadDir = dir;
874
875 upload.array('files')(req, res, (err) =>
876 {
877 if (err) return res.status(500).json({ error: err.message });
878
879 const db = getDb();
880 for (const f of (req.files || []))
881 {
882 const filePath = path.join(dir, f.originalname);
883 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
884 if (existing)
885 {
886 db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')
887 .run([req.user.username, filePath]);
888 } else
889 {
890 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
891 .run([filePath, req.user.username, '[]']);
892 }
893 }
894 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
895 });
896});
897
898// ---------------------------------------------------------------------------
899// POST /api/files/rename
900// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
901// ---------------------------------------------------------------------------
902router.post('/rename', requireAuth, (req, res) =>
903{
904 const { from, to } = req.body;
905 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
906
907 // Prevent path traversal in the new name
908 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
909 {
910 return res.status(400).json({ error: 'Invalid name.' });
911 }
912
913 const roots = effectivePaths();
914 const info = resolveRoot(from, roots);
915 if (!info || !canWrite(req.user, info.label))
916 {
917 return res.status(403).json({ error: 'Access denied.' });
918 }
919
920 const dest = path.join(path.dirname(from), to);
921
922 // Ensure dest is still inside the same root
923 if (!getAllowedRoot(dest, roots))
924 {
925 return res.status(403).json({ error: 'Access denied.' });
926 }
927
928 try
929 {
930 fs.renameSync(from, dest);
931 } catch (err)
932 {
933 return res.status(500).json({ error: err.message });
934 }
935
936 rewriteMetaPaths(from, dest);
937
938 res.json({ ok: true });
939});
940
941// ---------------------------------------------------------------------------
942// POST /api/files/move
943// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
944// ---------------------------------------------------------------------------
945router.post('/move', requireAuth, (req, res) =>
946{
947 const { from, toDir } = req.body;
948 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
949 const targetName = req.body && req.body.targetName != null
950 ? String(req.body.targetName).trim()
951 : '';
952 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
953 if (!['error', 'overwrite', 'rename'].includes(conflict))
954 {
955 return res.status(400).json({ error: 'Invalid conflict strategy.' });
956 }
957
958 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
959 {
960 return res.status(400).json({ error: 'Invalid targetName.' });
961 }
962
963 const roots = effectivePaths();
964 const fromInfo = resolveRoot(from, roots);
965 const toInfo = resolveRoot(toDir, roots);
966 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
967 if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))
968 {
969 return res.status(403).json({ error: 'Access denied.' });
970 }
971
972 let sourceStat;
973 let destStat;
974 try
975 {
976 sourceStat = fs.statSync(from);
977 destStat = fs.statSync(toDir);
978 } catch
979 {
980 return res.status(404).json({ error: 'Source or destination not found.' });
981 }
982
983 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
984
985 const requestedName = targetName || path.basename(from);
986 const requestedDest = path.join(toDir, requestedName);
987 if (!getAllowedRoot(requestedDest, roots)) return res.status(403).json({ error: 'Access denied.' });
988 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
989 {
990 return res.status(400).json({ error: 'Cannot move onto itself.' });
991 }
992 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
993 {
994 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
995 }
996
997 let dest = requestedDest;
998 let resolvedConflict = 'none';
999
1000 if (fs.existsSync(requestedDest))
1001 {
1002 if (conflict === 'error')
1003 {
1004 return res.status(409).json({ error: 'Destination already exists.' });
1005 }
1006
1007 if (conflict === 'rename')
1008 {
1009 dest = pickNumberedPath(toDir, requestedName);
1010 resolvedConflict = 'rename';
1011 }
1012
1013 if (conflict === 'overwrite')
1014 {
1015 try
1016 {
1017 removePathRecursive(requestedDest);
1018 } catch (err)
1019 {
1020 return res.status(500).json({ error: err.message });
1021 }
1022 resolvedConflict = 'overwrite';
1023 }
1024 }
1025
1026 if (sameResolvedPath(from, dest))
1027 {
1028 return res.status(400).json({ error: 'Cannot move onto itself.' });
1029 }
1030
1031 try
1032 {
1033 fs.renameSync(from, dest);
1034 } catch (err)
1035 {
1036 return res.status(500).json({ error: err.message });
1037 }
1038
1039 rewriteMetaPaths(from, dest);
1040 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1041});
1042
1043// ---------------------------------------------------------------------------
1044// POST /api/files/mkdir
1045// Body: { dir: <absolute-path>, name: <folder-name> }
1046// ---------------------------------------------------------------------------
1047router.post('/mkdir', requireAuth, (req, res) =>
1048{
1049 const { dir, name } = req.body;
1050 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
1051
1052 if (path.basename(name) !== name)
1053 {
1054 return res.status(400).json({ error: 'Invalid folder name.' });
1055 }
1056
1057 const roots = effectivePaths();
1058 const info = resolveRoot(dir, roots);
1059 if (!info || !canWrite(req.user, info.label))
1060 {
1061 return res.status(403).json({ error: 'Access denied.' });
1062 }
1063
1064 const newDir = path.join(dir, name);
1065 if (!getAllowedRoot(newDir, roots))
1066 {
1067 return res.status(403).json({ error: 'Access denied.' });
1068 }
1069
1070 try
1071 {
1072 fs.mkdirSync(newDir, { recursive: false });
1073 } catch (err)
1074 {
1075 return res.status(500).json({ error: err.message });
1076 }
1077
1078 res.json({ ok: true, path: newDir });
1079});
1080
1081// ---------------------------------------------------------------------------
1082// POST /api/files/delete
1083// Body: { path: <absolute-path> }
1084// ---------------------------------------------------------------------------
1085router.post('/delete', requireAuth, (req, res) =>
1086{
1087 const target = req.body.path;
1088 if (!target) return res.status(400).json({ error: 'path is required.' });
1089
1090 const roots = effectivePaths();
1091 const info = resolveRoot(target, roots);
1092 if (!info || !canWrite(req.user, info.label))
1093 {
1094 return res.status(403).json({ error: 'Access denied.' });
1095 }
1096
1097 // Do not allow deleting a configured root itself
1098 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
1099 {
1100 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
1101 }
1102
1103 try
1104 {
1105 const stat = fs.statSync(target);
1106 if (stat.isDirectory())
1107 {
1108 fs.rmSync(target, { recursive: true, force: true });
1109 } else
1110 {
1111 fs.unlinkSync(target);
1112 }
1113 } catch (err)
1114 {
1115 return res.status(500).json({ error: err.message });
1116 }
1117
1118 // Clean up any DB meta entries under that path
1119 const db = getDb();
1120 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
1121 .run([target, target + path.sep + '%']);
1122
1123 res.json({ ok: true });
1124});
1125
1126// ---------------------------------------------------------------------------
1127// GET /api/files/folder-images?dir=<absolute-path>
1128// Returns images inside dir (recursive) that already have a cached thumbnail.
1129// Only images with a ready thumbnail are included (user constraint).
1130// ---------------------------------------------------------------------------
1131router.get('/folder-images', requireAuth, async (req, res) =>
1132{
1133 const dir = String(req.query.dir || '').trim();
1134 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1135
1136 const roots = effectivePaths();
1137 const info = resolveRoot(dir, roots);
1138 if (!info || !canRead(req.user, info.label))
1139 {
1140 return res.status(403).json({ error: 'Access denied.' });
1141 }
1142
1143 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1144 {
1145 return res.status(404).json({ error: 'Directory not found.' });
1146 }
1147
1148 const images = await getImagesWithThumbnailsInDir(dir);
1149 // Filter out any that escaped to a different root (safety check).
1150 const filtered = images.filter(({ filePath }) => !!getAllowedRoot(filePath, roots));
1151
1152 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1153});
1154
1155// ---------------------------------------------------------------------------
1156// GET /api/files/folder-icon?dir=<absolute-path>
1157// Returns the current icon source file for a folder (explicit or auto-first).
1158// ---------------------------------------------------------------------------
1159router.get('/folder-icon', requireAuth, async (req, res) =>
1160{
1161 const dir = String(req.query.dir || '').trim();
1162 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1163
1164 const roots = effectivePaths();
1165 const info = resolveRoot(dir, roots);
1166 if (!info || !canRead(req.user, info.label))
1167 {
1168 return res.status(403).json({ error: 'Access denied.' });
1169 }
1170
1171 const sourceFile = await getFolderIconSourceFile(dir);
1172 if (!sourceFile) return res.json({ icon: null });
1173
1174 // Verify the source is still accessible within a configured root.
1175 if (!getAllowedRoot(sourceFile, roots)) return res.json({ icon: null });
1176
1177 res.json({ icon: { filePath: sourceFile } });
1178});
1179
1180// ---------------------------------------------------------------------------
1181// POST /api/files/folder-icon
1182// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
1183// Requires write access; the image must already have a cached thumbnail.
1184// ---------------------------------------------------------------------------
1185router.post('/folder-icon', requireAuth, async (req, res) =>
1186{
1187 const folderPath = String((req.body && req.body.folderPath) || '').trim();
1188 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
1189
1190 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1191
1192 const roots = effectivePaths();
1193 const info = resolveRoot(folderPath, roots);
1194 if (!info || !canWrite(req.user, info.label))
1195 {
1196 return res.status(403).json({ error: 'Access denied.' });
1197 }
1198
1199 let stat;
1200 try { stat = fs.statSync(folderPath); }
1201 catch { return res.status(404).json({ error: 'Folder not found.' }); }
1202 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
1203
1204 if (rawImage !== null)
1205 {
1206 // Verify the image is inside a readable root.
1207 const imageRoot = getAllowedRoot(rawImage, roots);
1208 if (!imageRoot) return res.status(403).json({ error: 'Image not accessible.' });
1209
1210 // Must already have a cached thumbnail — only thumbnailed images can be selected.
1211 const thumb = await getCachedThumbnailInfo(rawImage);
1212 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
1213 }
1214
1215 await setFolderIconAssignment(folderPath, rawImage);
1216 res.json({ ok: true });
1217});
1218
1219module.exports = router;