70 lines
2.0 KiB
JavaScript
70 lines
2.0 KiB
JavaScript
const express = require('express');
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
const app = express();
|
|
const { logger, initializeLogging } = require('./logger');
|
|
const { setupSecurity } = require('./security');
|
|
|
|
const FILES_DIR = path.join(__dirname, 'files');
|
|
|
|
// Initialize the logging system
|
|
initializeLogging();
|
|
|
|
// Setup security middlewares
|
|
setupSecurity(app);
|
|
|
|
app.use(express.static(path.join(__dirname, 'public')));
|
|
|
|
// List directory contents
|
|
app.get('/api/list', (req, res) => {
|
|
const subpath = req.query.path || '';
|
|
const dirPath = path.join(FILES_DIR, subpath);
|
|
|
|
if (!dirPath.startsWith(FILES_DIR)) return res.status(400).send('Invalid path.');
|
|
|
|
fs.readdir(dirPath, { withFileTypes: true }, (err, items) => {
|
|
if (err) return res.status(500).send('Error reading directory.');
|
|
|
|
const result = items.map(item => ({
|
|
name: item.name,
|
|
isDirectory: item.isDirectory()
|
|
}));
|
|
|
|
res.json(result);
|
|
});
|
|
});
|
|
|
|
// Search for files recursively
|
|
function searchFiles(dir, term, basePath = '') {
|
|
let results = [];
|
|
|
|
const items = fs.readdirSync(dir, { withFileTypes: true });
|
|
for (const item of items) {
|
|
const fullPath = path.join(dir, item.name);
|
|
const relPath = path.join(basePath, item.name);
|
|
|
|
if (item.isDirectory()) {
|
|
results = results.concat(searchFiles(fullPath, term, relPath));
|
|
} else if (item.name.toLowerCase().includes(term.toLowerCase())) {
|
|
results.push(relPath);
|
|
}
|
|
}
|
|
return results;
|
|
}
|
|
|
|
app.get('/api/search', (req, res) => {
|
|
const term = req.query.q || '';
|
|
const results = searchFiles(FILES_DIR, term);
|
|
res.json(results);
|
|
});
|
|
|
|
// Download endpoint
|
|
app.get('/api/download', (req, res) => {
|
|
const filePath = path.join(FILES_DIR, req.query.path);
|
|
if (!filePath.startsWith(FILES_DIR)) return res.status(400).send('Invalid file path.');
|
|
res.download(filePath);
|
|
});
|
|
|
|
const PORT = 3300;
|
|
app.listen(PORT, () => console.log(`Server running at http://localhost:${PORT}`));
|