BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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