BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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