'use strict'; const express = require('express'); const path = require('path'); const fs = require('fs'); const multer = require('multer'); const router = express.Router(); const { getDb } = require('../db'); const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config'); const { requireAuth } = require('../auth'); // --------------------------------------------------------------------------- // Multer storage — files are written directly to the target directory // --------------------------------------------------------------------------- const storage = multer.diskStorage({ destination(req, file, cb) { // The target directory is resolved in the route handler, so we stash it // during the multer middleware call via req._uploadDir. cb(null, req._uploadDir); }, filename(req, file, cb) { cb(null, file.originalname); }, }); const upload = multer({ storage, limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB }); // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- function effectivePaths() { return getEffectivePaths(loadConfig().paths || []); } /** * Verify that the user has read access to the given configured-path label. * `pathLabel` is the base-name of the effective path (shown in the UI). */ function canRead(user, pathLabel) { if (user.isAdmin) return true; return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read); } function canWrite(user, pathLabel) { if (user.isAdmin) return true; return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write); } /** * Given an absolute path and the effective-paths list, return * { root, label } where label is the base-name of the root, or null. */ function resolveRoot(absPath, roots) { const matchedRoot = getAllowedRoot(absPath, roots); if (!matchedRoot) return null; return { root: matchedRoot, label: path.basename(matchedRoot) }; } // --------------------------------------------------------------------------- // GET /api/files/roots // Returns the effective configured paths the user can read. // --------------------------------------------------------------------------- router.get('/roots', requireAuth, (req, res) => { const roots = effectivePaths(); const readable = roots .filter(r => canRead(req.user, path.basename(r))) .map(r => ({ label: path.basename(r), path: r })); res.json({ roots: readable }); }); // --------------------------------------------------------------------------- // GET /api/files/list?dir= // Lists files and folders in the given directory. // --------------------------------------------------------------------------- router.get('/list', requireAuth, (req, res) => { const dir = req.query.dir; if (!dir) return res.status(400).json({ error: 'dir is required.' }); const roots = effectivePaths(); const info = resolveRoot(dir, roots); if (!info) return res.status(403).json({ error: 'Access denied.' }); if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' }); let entries; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return res.status(404).json({ error: 'Directory not found.' }); } const items = entries.map(e => { const fullPath = path.join(dir, e.name); let size = null; let mtime = null; try { const stat = fs.statSync(fullPath); size = stat.size; mtime = stat.mtime.toISOString(); } catch { /* ignore */ } return { name: e.name, isDir: e.isDirectory(), size, mtime, path: fullPath, }; }); res.json({ items }); }); // --------------------------------------------------------------------------- // GET /api/files/meta?file= // Returns file metadata from the DB. // --------------------------------------------------------------------------- router.get('/meta', requireAuth, (req, res) => { const file = req.query.file; if (!file) return res.status(400).json({ error: 'file is required.' }); const roots = effectivePaths(); const info = resolveRoot(file, roots); if (!info || !canRead(req.user, info.label)) { return res.status(403).json({ error: 'Access denied.' }); } let stat; try { stat = fs.statSync(file); } catch { return res.status(404).json({ error: 'File not found.' }); } const db = getDb(); const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]); res.json({ name: path.basename(file), size: stat.size, mtime: stat.mtime.toISOString(), uploader: meta ? meta.uploader : '', downloaders: meta ? JSON.parse(meta.downloaders) : [], }); }); // --------------------------------------------------------------------------- // GET /api/files/download?file= // Streams the file to the client; records the download. // --------------------------------------------------------------------------- router.get('/download', requireAuth, (req, res) => { const file = req.query.file; if (!file) return res.status(400).json({ error: 'file is required.' }); const roots = effectivePaths(); const info = resolveRoot(file, roots); if (!info || !canRead(req.user, info.label)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } // Record download const db = getDb(); const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]); if (meta) { const downloaders = JSON.parse(meta.downloaders); if (!downloaders.includes(req.user.username)) { downloaders.push(req.user.username); db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?') .run([JSON.stringify(downloaders), file]); } } else { db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') .run([file, '', JSON.stringify([req.user.username])]); } res.download(file, path.basename(file)); }); // --------------------------------------------------------------------------- // POST /api/files/upload?dir= // Accepts multipart file upload. // --------------------------------------------------------------------------- router.post('/upload', requireAuth, (req, res, next) => { const dir = req.query.dir; if (!dir) return res.status(400).json({ error: 'dir is required.' }); const roots = effectivePaths(); const info = resolveRoot(dir, roots); if (!info || !canWrite(req.user, info.label)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) { return res.status(404).json({ error: 'Directory not found.' }); } req._uploadDir = dir; upload.array('files')(req, res, (err) => { if (err) return res.status(500).json({ error: err.message }); const db = getDb(); for (const f of (req.files || [])) { const filePath = path.join(dir, f.originalname); const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]); if (existing) { db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?') .run([req.user.username, filePath]); } else { db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') .run([filePath, req.user.username, '[]']); } } res.json({ uploaded: (req.files || []).map(f => f.originalname) }); }); }); // --------------------------------------------------------------------------- // POST /api/files/rename // Body: { from: , to: } (to = just the filename, not full path) // --------------------------------------------------------------------------- router.post('/rename', requireAuth, (req, res) => { const { from, to } = req.body; if (!from || !to) return res.status(400).json({ error: 'from and to are required.' }); // Prevent path traversal in the new name if (path.basename(to) !== to || to.includes('/') || to.includes('\\')) { return res.status(400).json({ error: 'Invalid name.' }); } const roots = effectivePaths(); const info = resolveRoot(from, roots); if (!info || !canWrite(req.user, info.label)) { return res.status(403).json({ error: 'Access denied.' }); } const dest = path.join(path.dirname(from), to); // Ensure dest is still inside the same root if (!getAllowedRoot(dest, roots)) { return res.status(403).json({ error: 'Access denied.' }); } try { fs.renameSync(from, dest); } catch (err) { return res.status(500).json({ error: err.message }); } // Update DB meta key const db = getDb(); db.prepare('UPDATE file_meta SET file_path = ? WHERE file_path = ?').run([dest, from]); res.json({ ok: true }); }); // --------------------------------------------------------------------------- // POST /api/files/mkdir // Body: { dir: , name: } // --------------------------------------------------------------------------- router.post('/mkdir', requireAuth, (req, res) => { const { dir, name } = req.body; if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' }); if (path.basename(name) !== name) { return res.status(400).json({ error: 'Invalid folder name.' }); } const roots = effectivePaths(); const info = resolveRoot(dir, roots); if (!info || !canWrite(req.user, info.label)) { return res.status(403).json({ error: 'Access denied.' }); } const newDir = path.join(dir, name); if (!getAllowedRoot(newDir, roots)) { return res.status(403).json({ error: 'Access denied.' }); } try { fs.mkdirSync(newDir, { recursive: false }); } catch (err) { return res.status(500).json({ error: err.message }); } res.json({ ok: true, path: newDir }); }); // --------------------------------------------------------------------------- // POST /api/files/delete // Body: { path: } // --------------------------------------------------------------------------- router.post('/delete', requireAuth, (req, res) => { const target = req.body.path; if (!target) return res.status(400).json({ error: 'path is required.' }); const roots = effectivePaths(); const info = resolveRoot(target, roots); if (!info || !canWrite(req.user, info.label)) { return res.status(403).json({ error: 'Access denied.' }); } // Do not allow deleting a configured root itself if (roots.map(r => path.resolve(r)).includes(path.resolve(target))) { return res.status(403).json({ error: 'Cannot delete a configured root path.' }); } try { const stat = fs.statSync(target); if (stat.isDirectory()) { fs.rmSync(target, { recursive: true, force: true }); } else { fs.unlinkSync(target); } } catch (err) { return res.status(500).json({ error: err.message }); } // Clean up any DB meta entries under that path const db = getDb(); db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?") .run([target, target + path.sep + '%']); res.json({ ok: true }); }); module.exports = router;