BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

fixes and updates
timfa Tim Falken · pushed by timfa · 6 months ago
0ae63c84 History
files.js 13.4 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, getEffectivePaths, getAllowedRoot } = require('../config');
11const { requireAuth } = require('../auth');
12
13// ---------------------------------------------------------------------------
14// Multer storage — files are written directly to the target directory
15// ---------------------------------------------------------------------------
16const storage = multer.diskStorage({
17 destination (req, file, cb)
18 {
19 // The target directory is resolved in the route handler, so we stash it
20 // during the multer middleware call via req._uploadDir.
21 cb(null, req._uploadDir);
22 },
23 filename (req, file, cb)
24 {
25 cb(null, file.originalname);
26 },
27});
28
29const upload = multer({
30 storage,
31 limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB
32});
33
34// ---------------------------------------------------------------------------
35// Helpers
36// ---------------------------------------------------------------------------
37
38function effectivePaths ()
39{
40 return getEffectivePaths(loadConfig().paths || []);
41}
42
43function getFreeBytes (targetPath)
44{
45 if (typeof fs.statfsSync !== 'function') return null;
46 try
47 {
48 const stat = fs.statfsSync(targetPath);
49 if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null;
50 return stat.bavail * stat.bsize;
51 } catch
52 {
53 return null;
54 }
55}
56
57function getRecursiveSize (targetPath)
58{
59 try
60 {
61 const stat = fs.statSync(targetPath);
62 if (!stat.isDirectory()) return stat.size;
63 } catch
64 {
65 return 0;
66 }
67
68 let total = 0;
69 let entries = [];
70 try
71 {
72 entries = fs.readdirSync(targetPath, { withFileTypes: true });
73 } catch
74 {
75 return 0;
76 }
77
78 for (const entry of entries)
79 {
80 const child = path.join(targetPath, entry.name);
81 if (entry.isDirectory())
82 {
83 total += getRecursiveSize(child);
84 continue;
85 }
86 try
87 {
88 total += fs.statSync(child).size;
89 } catch
90 {
91 // Ignore files that disappear during traversal.
92 }
93 }
94
95 return total;
96}
97
98/**
99 * Verify that the user has read access to the given configured-path label.
100 * `pathLabel` is the base-name of the effective path (shown in the UI).
101 */
102function canRead (user, pathLabel)
103{
104 if (user.isAdmin) return true;
105 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
106}
107
108function canWrite (user, pathLabel)
109{
110 if (user.isAdmin) return true;
111 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
112}
113
114/**
115 * Given an absolute path and the effective-paths list, return
116 * { root, label } where label is the base-name of the root, or null.
117 */
118function resolveRoot (absPath, roots)
119{
120 const matchedRoot = getAllowedRoot(absPath, roots);
121 if (!matchedRoot) return null;
122 return { root: matchedRoot, label: path.basename(matchedRoot) };
123}
124
125// ---------------------------------------------------------------------------
126// GET /api/files/roots
127// Returns the effective configured paths the user can read.
128// ---------------------------------------------------------------------------
129router.get('/roots', requireAuth, (req, res) =>
130{
131 const roots = effectivePaths();
132 const readable = roots
133 .filter(r => canRead(req.user, path.basename(r)))
134 .map(r => ({ label: path.basename(r), path: r }));
135 res.json({ roots: readable });
136});
137
138// ---------------------------------------------------------------------------
139// GET /api/files/list?dir=<absolute-path>
140// Lists files and folders in the given directory.
141// ---------------------------------------------------------------------------
142router.get('/list', requireAuth, (req, res) =>
143{
144 const dir = req.query.dir;
145 if (!dir) return res.status(400).json({ error: 'dir is required.' });
146
147 const roots = effectivePaths();
148 const info = resolveRoot(dir, roots);
149 if (!info) return res.status(403).json({ error: 'Access denied.' });
150 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
151
152 let entries;
153 try
154 {
155 entries = fs.readdirSync(dir, { withFileTypes: true });
156 } catch
157 {
158 return res.status(404).json({ error: 'Directory not found.' });
159 }
160
161 const items = entries.map(e =>
162 {
163 const fullPath = path.join(dir, e.name);
164 let size = null;
165 let mtime = null;
166 try
167 {
168 const stat = fs.statSync(fullPath);
169 size = stat.size;
170 mtime = stat.mtime.toISOString();
171 } catch { /* ignore */ }
172
173 return {
174 name: e.name,
175 isDir: e.isDirectory(),
176 size,
177 mtime,
178 path: fullPath,
179 };
180 });
181
182 res.json({ items });
183});
184
185// ---------------------------------------------------------------------------
186// GET /api/files/meta?file=<absolute-path>
187// Returns file metadata from the DB.
188// ---------------------------------------------------------------------------
189router.get('/meta', requireAuth, (req, res) =>
190{
191 const file = req.query.file;
192 if (!file) return res.status(400).json({ error: 'file is required.' });
193
194 const roots = effectivePaths();
195 const info = resolveRoot(file, roots);
196 if (!info || !canRead(req.user, info.label))
197 {
198 return res.status(403).json({ error: 'Access denied.' });
199 }
200
201 let stat;
202 try
203 {
204 stat = fs.statSync(file);
205 } catch
206 {
207 return res.status(404).json({ error: 'File not found.' });
208 }
209
210 const db = getDb();
211 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
212
213 res.json({
214 name: path.basename(file),
215 size: stat.size,
216 mtime: stat.mtime.toISOString(),
217 uploader: meta ? meta.uploader : '',
218 downloaders: meta ? JSON.parse(meta.downloaders) : [],
219 });
220});
221
222// ---------------------------------------------------------------------------
223// GET /api/files/space?dir=<absolute-path>
224// Returns recursive used bytes for dir and available bytes on its root fs.
225// ---------------------------------------------------------------------------
226router.get('/space', requireAuth, (req, res) =>
227{
228 const dir = req.query.dir;
229 if (!dir) return res.status(400).json({ error: 'dir is required.' });
230
231 const roots = effectivePaths();
232 const info = resolveRoot(dir, roots);
233 if (!info || !canRead(req.user, info.label))
234 {
235 return res.status(403).json({ error: 'Access denied.' });
236 }
237
238 if (!fs.existsSync(dir))
239 {
240 return res.status(404).json({ error: 'Path not found.' });
241 }
242
243 const usedBytes = getRecursiveSize(dir);
244 const freeBytes = getFreeBytes(info.root);
245 res.json({
246 usedBytes,
247 freeBytes,
248 rootPath: info.root,
249 rootLabel: info.label,
250 });
251});
252
253// ---------------------------------------------------------------------------
254// GET /api/files/download?file=<absolute-path>
255// Streams the file to the client; records the download.
256// ---------------------------------------------------------------------------
257router.get('/download', requireAuth, (req, res) =>
258{
259 const file = req.query.file;
260 if (!file) return res.status(400).json({ error: 'file is required.' });
261
262 const roots = effectivePaths();
263 const info = resolveRoot(file, roots);
264 if (!info || !canRead(req.user, info.label))
265 {
266 return res.status(403).json({ error: 'Access denied.' });
267 }
268
269 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
270 {
271 return res.status(404).json({ error: 'File not found.' });
272 }
273
274 // Record download
275 const db = getDb();
276 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
277 if (meta)
278 {
279 const downloaders = JSON.parse(meta.downloaders);
280 if (!downloaders.includes(req.user.username))
281 {
282 downloaders.push(req.user.username);
283 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
284 .run([JSON.stringify(downloaders), file]);
285 }
286 } else
287 {
288 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
289 .run([file, '', JSON.stringify([req.user.username])]);
290 }
291
292 res.download(file, path.basename(file));
293});
294
295// ---------------------------------------------------------------------------
296// POST /api/files/upload?dir=<absolute-path>
297// Accepts multipart file upload.
298// ---------------------------------------------------------------------------
299router.post('/upload', requireAuth, (req, res, next) =>
300{
301 const dir = req.query.dir;
302 if (!dir) return res.status(400).json({ error: 'dir is required.' });
303
304 const roots = effectivePaths();
305 const info = resolveRoot(dir, roots);
306 if (!info || !canWrite(req.user, info.label))
307 {
308 return res.status(403).json({ error: 'Access denied.' });
309 }
310
311 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
312 {
313 return res.status(404).json({ error: 'Directory not found.' });
314 }
315
316 const announcedSize = Number(req.header('x-upload-size') || 0);
317 if (Number.isFinite(announcedSize) && announcedSize > 0)
318 {
319 const freeBytes = getFreeBytes(info.root);
320 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
321 {
322 return res.status(413).json({
323 error: 'Upload too large for remaining free space on selected root.',
324 freeBytes,
325 requiredBytes: announcedSize,
326 });
327 }
328 }
329
330 req._uploadDir = dir;
331
332 upload.array('files')(req, res, (err) =>
333 {
334 if (err) return res.status(500).json({ error: err.message });
335
336 const db = getDb();
337 for (const f of (req.files || []))
338 {
339 const filePath = path.join(dir, f.originalname);
340 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
341 if (existing)
342 {
343 db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')
344 .run([req.user.username, filePath]);
345 } else
346 {
347 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
348 .run([filePath, req.user.username, '[]']);
349 }
350 }
351 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
352 });
353});
354
355// ---------------------------------------------------------------------------
356// POST /api/files/rename
357// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
358// ---------------------------------------------------------------------------
359router.post('/rename', requireAuth, (req, res) =>
360{
361 const { from, to } = req.body;
362 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
363
364 // Prevent path traversal in the new name
365 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
366 {
367 return res.status(400).json({ error: 'Invalid name.' });
368 }
369
370 const roots = effectivePaths();
371 const info = resolveRoot(from, roots);
372 if (!info || !canWrite(req.user, info.label))
373 {
374 return res.status(403).json({ error: 'Access denied.' });
375 }
376
377 const dest = path.join(path.dirname(from), to);
378
379 // Ensure dest is still inside the same root
380 if (!getAllowedRoot(dest, roots))
381 {
382 return res.status(403).json({ error: 'Access denied.' });
383 }
384
385 try
386 {
387 fs.renameSync(from, dest);
388 } catch (err)
389 {
390 return res.status(500).json({ error: err.message });
391 }
392
393 // Update DB meta key
394 const db = getDb();
395 db.prepare('UPDATE file_meta SET file_path = ? WHERE file_path = ?').run([dest, from]);
396
397 res.json({ ok: true });
398});
399
400// ---------------------------------------------------------------------------
401// POST /api/files/mkdir
402// Body: { dir: <absolute-path>, name: <folder-name> }
403// ---------------------------------------------------------------------------
404router.post('/mkdir', requireAuth, (req, res) =>
405{
406 const { dir, name } = req.body;
407 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
408
409 if (path.basename(name) !== name)
410 {
411 return res.status(400).json({ error: 'Invalid folder name.' });
412 }
413
414 const roots = effectivePaths();
415 const info = resolveRoot(dir, roots);
416 if (!info || !canWrite(req.user, info.label))
417 {
418 return res.status(403).json({ error: 'Access denied.' });
419 }
420
421 const newDir = path.join(dir, name);
422 if (!getAllowedRoot(newDir, roots))
423 {
424 return res.status(403).json({ error: 'Access denied.' });
425 }
426
427 try
428 {
429 fs.mkdirSync(newDir, { recursive: false });
430 } catch (err)
431 {
432 return res.status(500).json({ error: err.message });
433 }
434
435 res.json({ ok: true, path: newDir });
436});
437
438// ---------------------------------------------------------------------------
439// POST /api/files/delete
440// Body: { path: <absolute-path> }
441// ---------------------------------------------------------------------------
442router.post('/delete', requireAuth, (req, res) =>
443{
444 const target = req.body.path;
445 if (!target) return res.status(400).json({ error: 'path is required.' });
446
447 const roots = effectivePaths();
448 const info = resolveRoot(target, roots);
449 if (!info || !canWrite(req.user, info.label))
450 {
451 return res.status(403).json({ error: 'Access denied.' });
452 }
453
454 // Do not allow deleting a configured root itself
455 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
456 {
457 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
458 }
459
460 try
461 {
462 const stat = fs.statSync(target);
463 if (stat.isDirectory())
464 {
465 fs.rmSync(target, { recursive: true, force: true });
466 } else
467 {
468 fs.unlinkSync(target);
469 }
470 } catch (err)
471 {
472 return res.status(500).json({ error: err.message });
473 }
474
475 // Clean up any DB meta entries under that path
476 const db = getDb();
477 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
478 .run([target, target + path.sep + '%']);
479
480 res.json({ ok: true });
481});
482
483module.exports = router;