-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
288 lines (245 loc) · 8.28 KB
/
server.js
File metadata and controls
288 lines (245 loc) · 8.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
const express = require('express');
const fs = require('fs-extra');
const path = require('path');
const multer = require('multer');
const mime = require('mime-types');
const archiver = require('archiver');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;
const ROOT_DIR = '/mnt/test';
// Ensure root directory exists
fs.ensureDirSync(ROOT_DIR);
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
// Configure multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const uploadPath = req.body.path || ROOT_DIR;
const fullPath = path.join(ROOT_DIR, uploadPath.replace(ROOT_DIR, ''));
fs.ensureDirSync(fullPath);
cb(null, fullPath);
},
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({ storage });
// Helper function to get safe path
function getSafePath(relativePath) {
const safePath = path.join(ROOT_DIR, relativePath || '');
if (!safePath.startsWith(ROOT_DIR)) {
throw new Error('Invalid path');
}
return safePath;
}
// Helper function to get file info
async function getFileInfo(filePath, relativePath) {
const stats = await fs.stat(filePath);
const isDirectory = stats.isDirectory();
return {
name: path.basename(filePath),
path: relativePath,
isDirectory,
size: isDirectory ? null : stats.size,
modified: stats.mtime,
type: isDirectory ? 'folder' : mime.lookup(filePath) || 'unknown'
};
}
// Routes
// Get directory contents
app.get('/api/files', async (req, res) => {
try {
const relativePath = req.query.path || '';
const fullPath = getSafePath(relativePath);
if (!await fs.pathExists(fullPath)) {
return res.status(404).json({ error: 'Directory not found' });
}
const items = await fs.readdir(fullPath);
const fileInfos = [];
for (const item of items) {
const itemPath = path.join(fullPath, item);
const itemRelativePath = path.join(relativePath, item);
try {
const info = await getFileInfo(itemPath, itemRelativePath);
fileInfos.push(info);
} catch (err) {
console.warn(`Could not get info for ${item}:`, err.message);
}
}
// Sort: directories first, then files
fileInfos.sort((a, b) => {
if (a.isDirectory && !b.isDirectory) return -1;
if (!a.isDirectory && b.isDirectory) return 1;
return a.name.localeCompare(b.name);
});
res.json(fileInfos);
} catch (error) {
console.error('Error reading directory:', error);
res.status(500).json({ error: 'Failed to read directory' });
}
});
// Get directory tree (for sidebar)
app.get('/api/tree', async (req, res) => {
try {
async function buildTree(dirPath, relativePath = '') {
const items = await fs.readdir(dirPath);
const tree = [];
for (const item of items) {
const itemPath = path.join(dirPath, item);
const itemRelativePath = path.join(relativePath, item);
try {
const stats = await fs.stat(itemPath);
if (stats.isDirectory()) {
tree.push({
name: item,
path: itemRelativePath,
isDirectory: true,
children: await buildTree(itemPath, itemRelativePath)
});
}
} catch (err) {
console.warn(`Could not process ${item}:`, err.message);
}
}
return tree.sort((a, b) => a.name.localeCompare(b.name));
}
const tree = await buildTree(ROOT_DIR);
res.json(tree);
} catch (error) {
console.error('Error building tree:', error);
res.status(500).json({ error: 'Failed to build directory tree' });
}
});
// Create directory
app.post('/api/directory', async (req, res) => {
try {
const { path: relativePath, name } = req.body;
if (!name) {
return res.status(400).json({ error: 'Directory name is required' });
}
const parentPath = getSafePath(relativePath || '');
const newDirPath = path.join(parentPath, name);
await fs.ensureDir(newDirPath);
res.json({ message: 'Directory created successfully' });
} catch (error) {
console.error('Error creating directory:', error);
res.status(500).json({ error: 'Failed to create directory' });
}
});
// Upload files
app.post('/api/upload', upload.array('files'), (req, res) => {
try {
res.json({
message: 'Files uploaded successfully',
files: req.files.map(file => file.filename)
});
} catch (error) {
console.error('Error uploading files:', error);
res.status(500).json({ error: 'Failed to upload files' });
}
});
// Download file
app.get('/api/download', async (req, res) => {
try {
const relativePath = req.query.path;
if (!relativePath) {
return res.status(400).json({ error: 'File path is required' });
}
const filePath = getSafePath(relativePath);
if (!await fs.pathExists(filePath)) {
return res.status(404).json({ error: 'File not found' });
}
const stats = await fs.stat(filePath);
const fileName = path.basename(filePath);
if (stats.isDirectory()) {
// Create zip for directory
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', `attachment; filename="${fileName}.zip"`);
const archive = archiver('zip', { zlib: { level: 9 } });
archive.pipe(res);
archive.directory(filePath, false);
archive.finalize();
} else {
// Send file directly
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
res.sendFile(filePath);
}
} catch (error) {
console.error('Error downloading file:', error);
res.status(500).json({ error: 'Failed to download file' });
}
});
// Delete file/directory
app.delete('/api/files', async (req, res) => {
try {
const relativePath = req.query.path;
if (!relativePath) {
return res.status(400).json({ error: 'File path is required' });
}
const filePath = getSafePath(relativePath);
await fs.remove(filePath);
res.json({ message: 'File/directory deleted successfully' });
} catch (error) {
console.error('Error deleting file:', error);
res.status(500).json({ error: 'Failed to delete file/directory' });
}
});
// Copy file/directory
app.post('/api/copy', async (req, res) => {
try {
const { source, destination } = req.body;
if (!source || !destination) {
return res.status(400).json({ error: 'Source and destination paths are required' });
}
const sourcePath = getSafePath(source);
const destPath = getSafePath(destination);
await fs.copy(sourcePath, destPath);
res.json({ message: 'File/directory copied successfully' });
} catch (error) {
console.error('Error copying file:', error);
res.status(500).json({ error: 'Failed to copy file/directory' });
}
});
// Move file/directory
app.post('/api/move', async (req, res) => {
try {
const { source, destination } = req.body;
if (!source || !destination) {
return res.status(400).json({ error: 'Source and destination paths are required' });
}
const sourcePath = getSafePath(source);
const destPath = getSafePath(destination);
await fs.move(sourcePath, destPath);
res.json({ message: 'File/directory moved successfully' });
} catch (error) {
console.error('Error moving file:', error);
res.status(500).json({ error: 'Failed to move file/directory' });
}
});
// Get file properties
app.get('/api/properties', async (req, res) => {
try {
const relativePath = req.query.path;
if (!relativePath) {
return res.status(400).json({ error: 'File path is required' });
}
const filePath = getSafePath(relativePath);
const info = await getFileInfo(filePath, relativePath);
if (info.isDirectory) {
// Count directory contents
const contents = await fs.readdir(filePath);
info.itemCount = contents.length;
}
res.json(info);
} catch (error) {
console.error('Error getting file properties:', error);
res.status(500).json({ error: 'Failed to get file properties' });
}
});
app.listen(PORT, () => {
console.log(`File manager server running on http://localhost:${PORT}`);
console.log(`Managing directory: ${ROOT_DIR}`);
});