BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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