BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

files.js 19.3 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const path = require('path');
5const fs = require('fs');
6const multer = require('multer');
7const router = express.Router();
8
9const { getDb } = require('../db');
10const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
11const { requireAuth } = require('../auth');
12const { getCachedThumbnailInfo } = require('../thumbnail-cache');
13
14// ---------------------------------------------------------------------------
15// Multer storage — files are written directly to the target directory
16// ---------------------------------------------------------------------------
17const storage = multer.diskStorage({
18 destination (req, file, cb)
19 {
20 // The target directory is resolved in the route handler, so we stash it
21 // during the multer middleware call via req._uploadDir.
22 cb(null, req._uploadDir);
23 },
24 filename (req, file, cb)
25 {
26 cb(null, file.originalname);
27 },
28});
29
30const upload = multer({
31 storage,
32 limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB
33});
34
35// ---------------------------------------------------------------------------
36// Helpers
37// ---------------------------------------------------------------------------
38
39function effectivePaths ()
40{
41 return getEffectivePaths(loadConfig().paths || []);
42}
43
44function rootAliasesFromConfig (config)
45{
46 if (!config || typeof config !== 'object') return {};
47 if (!config.rootAliases || typeof config.rootAliases !== 'object') return {};
48 return config.rootAliases;
49}
50
51function getFreeBytes (targetPath)
52{
53 if (typeof fs.statfsSync !== 'function') return null;
54 try
55 {
56 const stat = fs.statfsSync(targetPath);
57 if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null;
58 return stat.bavail * stat.bsize;
59 } catch
60 {
61 return null;
62 }
63}
64
65function getRecursiveSize (targetPath)
66{
67 try
68 {
69 const stat = fs.statSync(targetPath);
70 if (!stat.isDirectory()) return stat.size;
71 } catch
72 {
73 return 0;
74 }
75
76 let total = 0;
77 let entries = [];
78 try
79 {
80 entries = fs.readdirSync(targetPath, { withFileTypes: true });
81 } catch
82 {
83 return 0;
84 }
85
86 for (const entry of entries)
87 {
88 const child = path.join(targetPath, entry.name);
89 if (entry.isDirectory())
90 {
91 total += getRecursiveSize(child);
92 continue;
93 }
94 try
95 {
96 total += fs.statSync(child).size;
97 } catch
98 {
99 // Ignore files that disappear during traversal.
100 }
101 }
102
103 return total;
104}
105
106/**
107 * Verify that the user has read access to the given configured-path label.
108 * `pathLabel` is the base-name of the effective path (shown in the UI).
109 */
110function canRead (user, pathLabel)
111{
112 if (user.isAdmin) return true;
113 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
114}
115
116function canWrite (user, pathLabel)
117{
118 if (user.isAdmin) return true;
119 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
120}
121
122/**
123 * Given an absolute path and the effective-paths list, return
124 * { root, label } where label is the base-name of the root, or null.
125 */
126function resolveRoot (absPath, roots)
127{
128 const matchedRoot = getAllowedRoot(absPath, roots);
129 if (!matchedRoot) return null;
130 return { root: matchedRoot, label: path.basename(matchedRoot) };
131}
132
133function sameResolvedPath (a, b)
134{
135 return path.resolve(String(a || '')) === path.resolve(String(b || ''));
136}
137
138function pathInsideResolved (child, root)
139{
140 const relative = path.relative(path.resolve(root), path.resolve(child));
141 return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
142}
143
144function rewriteMetaPaths (fromPath, toPath)
145{
146 const db = getDb();
147 const rows = db.prepare('SELECT file_path, uploader, downloaders FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
148 .all([fromPath, fromPath + path.sep + '%']);
149
150 if (!rows.length) return;
151
152 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
153 const upsert = db.prepare(`
154 INSERT INTO file_meta (file_path, uploader, downloaders)
155 VALUES (?, ?, ?)
156 ON CONFLICT(file_path) DO UPDATE SET
157 uploader = excluded.uploader,
158 downloaders = excluded.downloaders
159 `);
160
161 for (const row of rows)
162 {
163 const nextPath = row.file_path === fromPath
164 ? toPath
165 : toPath + row.file_path.slice(fromPath.length);
166 del.run([row.file_path]);
167 upsert.run([nextPath, row.uploader, row.downloaders]);
168 }
169}
170
171// ---------------------------------------------------------------------------
172// GET /api/files/roots
173// Returns the effective configured paths the user can read.
174// ---------------------------------------------------------------------------
175router.get('/roots', requireAuth, (req, res) =>
176{
177 const config = loadConfig();
178 const roots = getEffectivePaths(config.paths || []);
179 const rootAliases = rootAliasesFromConfig(config);
180
181 const readable = roots
182 .filter(r => canRead(req.user, path.basename(r)))
183 .map(r =>
184 {
185 const originalName = path.basename(r);
186 const alias = String(rootAliases[path.resolve(r)] || '').trim();
187 return {
188 label: alias || originalName,
189 path: r,
190 originalName,
191 alias: alias || null,
192 };
193 });
194 res.json({ roots: readable });
195});
196
197// ---------------------------------------------------------------------------
198// POST /api/files/root-alias
199// Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
200// Sets a display-only alias for a configured root.
201// ---------------------------------------------------------------------------
202router.post('/root-alias', requireAuth, (req, res) =>
203{
204 const rootPath = String(req.body && req.body.rootPath || '').trim();
205 const alias = String(req.body && req.body.alias || '').trim();
206 if (!rootPath || !alias)
207 {
208 return res.status(400).json({ error: 'rootPath and alias are required.' });
209 }
210
211 const roots = effectivePaths();
212 const info = resolveRoot(rootPath, roots);
213 if (!info) return res.status(403).json({ error: 'Access denied.' });
214 if (!sameResolvedPath(rootPath, info.root))
215 {
216 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
217 }
218 if (!canWrite(req.user, info.label))
219 {
220 return res.status(403).json({ error: 'Access denied.' });
221 }
222
223 const config = loadConfig();
224 const rootAliases = rootAliasesFromConfig(config);
225 const key = path.resolve(info.root);
226 if (alias === info.label)
227 {
228 delete rootAliases[key];
229 } else
230 {
231 rootAliases[key] = alias;
232 }
233 config.rootAliases = rootAliases;
234 saveConfig(config);
235
236 res.json({
237 ok: true,
238 root: {
239 path: info.root,
240 label: alias,
241 originalName: info.label,
242 alias,
243 },
244 });
245});
246
247// ---------------------------------------------------------------------------
248// GET /api/files/list?dir=<absolute-path>
249// Lists files and folders in the given directory.
250// ---------------------------------------------------------------------------
251router.get('/list', requireAuth, (req, res) =>
252{
253 const dir = req.query.dir;
254 if (!dir) return res.status(400).json({ error: 'dir is required.' });
255
256 const roots = effectivePaths();
257 const info = resolveRoot(dir, roots);
258 if (!info) return res.status(403).json({ error: 'Access denied.' });
259 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
260
261 let entries;
262 try
263 {
264 entries = fs.readdirSync(dir, { withFileTypes: true });
265 } catch
266 {
267 return res.status(404).json({ error: 'Directory not found.' });
268 }
269
270 const items = entries.map(e =>
271 {
272 const fullPath = path.join(dir, e.name);
273 let size = null;
274 let mtime = null;
275 try
276 {
277 const stat = fs.statSync(fullPath);
278 size = stat.size;
279 mtime = stat.mtime.toISOString();
280 } catch { /* ignore */ }
281
282 return {
283 name: e.name,
284 isDir: e.isDirectory(),
285 size,
286 mtime,
287 path: fullPath,
288 };
289 });
290
291 res.json({ items });
292});
293
294// ---------------------------------------------------------------------------
295// GET /api/files/meta?file=<absolute-path>
296// Returns file metadata from the DB.
297// ---------------------------------------------------------------------------
298router.get('/meta', requireAuth, (req, res) =>
299{
300 const file = req.query.file;
301 if (!file) return res.status(400).json({ error: 'file is required.' });
302
303 const roots = effectivePaths();
304 const info = resolveRoot(file, roots);
305 if (!info || !canRead(req.user, info.label))
306 {
307 return res.status(403).json({ error: 'Access denied.' });
308 }
309
310 let stat;
311 try
312 {
313 stat = fs.statSync(file);
314 } catch
315 {
316 return res.status(404).json({ error: 'File not found.' });
317 }
318
319 const db = getDb();
320 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
321
322 res.json({
323 name: path.basename(file),
324 size: stat.size,
325 mtime: stat.mtime.toISOString(),
326 uploader: meta ? meta.uploader : '',
327 downloaders: meta ? JSON.parse(meta.downloaders) : [],
328 });
329});
330
331// ---------------------------------------------------------------------------
332// GET /api/files/space?dir=<absolute-path>
333// Returns recursive used bytes for dir and available bytes on its root fs.
334// ---------------------------------------------------------------------------
335router.get('/space', requireAuth, (req, res) =>
336{
337 const dir = req.query.dir;
338 if (!dir) return res.status(400).json({ error: 'dir is required.' });
339
340 const roots = effectivePaths();
341 const info = resolveRoot(dir, roots);
342 if (!info || !canRead(req.user, info.label))
343 {
344 return res.status(403).json({ error: 'Access denied.' });
345 }
346
347 if (!fs.existsSync(dir))
348 {
349 return res.status(404).json({ error: 'Path not found.' });
350 }
351
352 const usedBytes = getRecursiveSize(dir);
353 const freeBytes = getFreeBytes(info.root);
354 res.json({
355 usedBytes,
356 freeBytes,
357 rootPath: info.root,
358 rootLabel: info.label,
359 });
360});
361
362// ---------------------------------------------------------------------------
363// GET /api/files/download?file=<absolute-path>
364// Streams the file to the client; records the download.
365// ---------------------------------------------------------------------------
366router.get('/download', requireAuth, (req, res) =>
367{
368 const file = req.query.file;
369 if (!file) return res.status(400).json({ error: 'file is required.' });
370
371 const roots = effectivePaths();
372 const info = resolveRoot(file, roots);
373 if (!info || !canRead(req.user, info.label))
374 {
375 return res.status(403).json({ error: 'Access denied.' });
376 }
377
378 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
379 {
380 return res.status(404).json({ error: 'File not found.' });
381 }
382
383 // Record download
384 const db = getDb();
385 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
386 if (meta)
387 {
388 const downloaders = JSON.parse(meta.downloaders);
389 if (!downloaders.includes(req.user.username))
390 {
391 downloaders.push(req.user.username);
392 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
393 .run([JSON.stringify(downloaders), file]);
394 }
395 } else
396 {
397 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
398 .run([file, '', JSON.stringify([req.user.username])]);
399 }
400
401 res.download(file, path.basename(file));
402});
403
404// ---------------------------------------------------------------------------
405// GET /api/files/thumbnail?file=<absolute-path>
406// Returns a pre-generated cached thumbnail if present.
407// ---------------------------------------------------------------------------
408router.get('/thumbnail', requireAuth, async (req, res) =>
409{
410 const file = req.query.file;
411 if (!file) return res.status(400).json({ error: 'file is required.' });
412
413 const roots = effectivePaths();
414 const info = resolveRoot(file, roots);
415 if (!info || !canRead(req.user, info.label))
416 {
417 return res.status(403).json({ error: 'Access denied.' });
418 }
419
420 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
421 {
422 return res.status(404).json({ error: 'File not found.' });
423 }
424
425 const thumb = await getCachedThumbnailInfo(file);
426 if (!thumb)
427 {
428 return res.status(404).json({ error: 'Thumbnail not ready.' });
429 }
430
431 res.type(thumb.contentType);
432 res.set('Cache-Control', 'private, max-age=10');
433 res.sendFile(thumb.thumbPath);
434});
435
436// ---------------------------------------------------------------------------
437// POST /api/files/upload?dir=<absolute-path>
438// Accepts multipart file upload.
439// ---------------------------------------------------------------------------
440router.post('/upload', requireAuth, (req, res, next) =>
441{
442 const dir = req.query.dir;
443 if (!dir) return res.status(400).json({ error: 'dir is required.' });
444
445 const roots = effectivePaths();
446 const info = resolveRoot(dir, roots);
447 if (!info || !canWrite(req.user, info.label))
448 {
449 return res.status(403).json({ error: 'Access denied.' });
450 }
451
452 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
453 {
454 return res.status(404).json({ error: 'Directory not found.' });
455 }
456
457 const announcedSize = Number(req.header('x-upload-size') || 0);
458 if (Number.isFinite(announcedSize) && announcedSize > 0)
459 {
460 const freeBytes = getFreeBytes(info.root);
461 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
462 {
463 return res.status(413).json({
464 error: 'Upload too large for remaining free space on selected root.',
465 freeBytes,
466 requiredBytes: announcedSize,
467 });
468 }
469 }
470
471 req._uploadDir = dir;
472
473 upload.array('files')(req, res, (err) =>
474 {
475 if (err) return res.status(500).json({ error: err.message });
476
477 const db = getDb();
478 for (const f of (req.files || []))
479 {
480 const filePath = path.join(dir, f.originalname);
481 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
482 if (existing)
483 {
484 db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')
485 .run([req.user.username, filePath]);
486 } else
487 {
488 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
489 .run([filePath, req.user.username, '[]']);
490 }
491 }
492 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
493 });
494});
495
496// ---------------------------------------------------------------------------
497// POST /api/files/rename
498// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
499// ---------------------------------------------------------------------------
500router.post('/rename', requireAuth, (req, res) =>
501{
502 const { from, to } = req.body;
503 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
504
505 // Prevent path traversal in the new name
506 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
507 {
508 return res.status(400).json({ error: 'Invalid name.' });
509 }
510
511 const roots = effectivePaths();
512 const info = resolveRoot(from, roots);
513 if (!info || !canWrite(req.user, info.label))
514 {
515 return res.status(403).json({ error: 'Access denied.' });
516 }
517
518 const dest = path.join(path.dirname(from), to);
519
520 // Ensure dest is still inside the same root
521 if (!getAllowedRoot(dest, roots))
522 {
523 return res.status(403).json({ error: 'Access denied.' });
524 }
525
526 try
527 {
528 fs.renameSync(from, dest);
529 } catch (err)
530 {
531 return res.status(500).json({ error: err.message });
532 }
533
534 rewriteMetaPaths(from, dest);
535
536 res.json({ ok: true });
537});
538
539// ---------------------------------------------------------------------------
540// POST /api/files/move
541// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
542// ---------------------------------------------------------------------------
543router.post('/move', requireAuth, (req, res) =>
544{
545 const { from, toDir } = req.body;
546 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
547
548 const roots = effectivePaths();
549 const fromInfo = resolveRoot(from, roots);
550 const toInfo = resolveRoot(toDir, roots);
551 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
552 if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))
553 {
554 return res.status(403).json({ error: 'Access denied.' });
555 }
556
557 let sourceStat;
558 let destStat;
559 try
560 {
561 sourceStat = fs.statSync(from);
562 destStat = fs.statSync(toDir);
563 } catch
564 {
565 return res.status(404).json({ error: 'Source or destination not found.' });
566 }
567
568 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
569
570 const dest = path.join(toDir, path.basename(from));
571 if (!getAllowedRoot(dest, roots)) return res.status(403).json({ error: 'Access denied.' });
572 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, dest))
573 {
574 return res.status(400).json({ error: 'Cannot move onto itself.' });
575 }
576 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
577 {
578 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
579 }
580 if (fs.existsSync(dest)) return res.status(409).json({ error: 'Destination already exists.' });
581
582 try
583 {
584 fs.renameSync(from, dest);
585 } catch (err)
586 {
587 return res.status(500).json({ error: err.message });
588 }
589
590 rewriteMetaPaths(from, dest);
591 res.json({ ok: true, path: dest });
592});
593
594// ---------------------------------------------------------------------------
595// POST /api/files/mkdir
596// Body: { dir: <absolute-path>, name: <folder-name> }
597// ---------------------------------------------------------------------------
598router.post('/mkdir', requireAuth, (req, res) =>
599{
600 const { dir, name } = req.body;
601 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
602
603 if (path.basename(name) !== name)
604 {
605 return res.status(400).json({ error: 'Invalid folder name.' });
606 }
607
608 const roots = effectivePaths();
609 const info = resolveRoot(dir, roots);
610 if (!info || !canWrite(req.user, info.label))
611 {
612 return res.status(403).json({ error: 'Access denied.' });
613 }
614
615 const newDir = path.join(dir, name);
616 if (!getAllowedRoot(newDir, roots))
617 {
618 return res.status(403).json({ error: 'Access denied.' });
619 }
620
621 try
622 {
623 fs.mkdirSync(newDir, { recursive: false });
624 } catch (err)
625 {
626 return res.status(500).json({ error: err.message });
627 }
628
629 res.json({ ok: true, path: newDir });
630});
631
632// ---------------------------------------------------------------------------
633// POST /api/files/delete
634// Body: { path: <absolute-path> }
635// ---------------------------------------------------------------------------
636router.post('/delete', requireAuth, (req, res) =>
637{
638 const target = req.body.path;
639 if (!target) return res.status(400).json({ error: 'path is required.' });
640
641 const roots = effectivePaths();
642 const info = resolveRoot(target, roots);
643 if (!info || !canWrite(req.user, info.label))
644 {
645 return res.status(403).json({ error: 'Access denied.' });
646 }
647
648 // Do not allow deleting a configured root itself
649 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
650 {
651 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
652 }
653
654 try
655 {
656 const stat = fs.statSync(target);
657 if (stat.isDirectory())
658 {
659 fs.rmSync(target, { recursive: true, force: true });
660 } else
661 {
662 fs.unlinkSync(target);
663 }
664 } catch (err)
665 {
666 return res.status(500).json({ error: err.message });
667 }
668
669 // Clean up any DB meta entries under that path
670 const db = getDb();
671 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
672 .run([target, target + path.sep + '%']);
673
674 res.json({ ok: true });
675});
676
677module.exports = router;