Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
277 lines (234 loc) · 7.61 KB
/
Copy pathserver.js
File metadata and controls
277 lines (234 loc) · 7.61 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
const express = require('express');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { execSync } = require('child_process');
const app = express();
const PORT = 3847;
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
// Get home path
app.get('/api/home', (req, res) => {
res.json({ home: os.homedir() });
});
// Get disk overview
app.get('/api/disk-info', (req, res) => {
try {
const output = execSync("df -h / | tail -1").toString().trim();
const parts = output.split(/\s+/);
const totalRaw = execSync("df -k / | tail -1").toString().trim().split(/\s+/);
res.json({
filesystem: parts[0],
total: parts[1],
used: parts[2],
available: parts[3],
usedPercent: parseInt(parts[4]),
totalBytes: parseInt(totalRaw[1]) * 1024,
usedBytes: parseInt(totalRaw[2]) * 1024,
availableBytes: parseInt(totalRaw[3]) * 1024,
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Scan a directory
app.get('/api/scan', (req, res) => {
let targetPath = req.query.path || os.homedir();
if (targetPath === '~') targetPath = os.homedir();
const depthLimit = parseInt(req.query.depth) || 1;
try {
const realPath = fs.realpathSync(targetPath);
const results = scanDirectory(realPath, depthLimit, 0);
results.sort((a, b) => b.size - a.size);
res.json({
path: realPath,
children: results,
totalSize: results.reduce((sum, item) => sum + item.size, 0),
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Quick scan using a single du call for all top-level entries
app.get('/api/quick-scan', (req, res) => {
let targetPath = req.query.path || os.homedir();
if (targetPath === '~') targetPath = os.homedir();
try {
const realPath = fs.realpathSync(targetPath);
let entries;
try {
entries = fs.readdirSync(realPath, { withFileTypes: true });
} catch {
return res.json({ path: realPath, children: [], totalSize: 0 });
}
// Use a single du -sk -d 0 on each item via xargs for speed
const sizeMap = {};
try {
const duOutput = execSync(
`du -sk "${realPath}"/* "${realPath}"/.[!.]* 2>/dev/null || true`,
{ timeout: 30000, maxBuffer: 10 * 1024 * 1024 }
).toString().trim();
for (const line of duOutput.split('\n')) {
if (!line) continue;
const match = line.match(/^(\d+)\s+(.+)$/);
if (match) {
sizeMap[match[2]] = parseInt(match[1]) * 1024;
}
}
} catch {
// Fallback: sizes will be 0
}
const results = [];
for (const entry of entries) {
try {
if (entry.isSymbolicLink()) continue;
const fullPath = path.join(realPath, entry.name);
const isDir = entry.isDirectory();
let size = sizeMap[fullPath] || 0;
if (!isDir && size === 0) {
try {
const stats = fs.statSync(fullPath);
size = stats.size;
} catch {}
}
results.push({
name: entry.name,
path: fullPath,
size,
isDirectory: isDir,
children: [],
});
} catch {
// Skip inaccessible items
}
}
results.sort((a, b) => b.size - a.size);
const totalSize = results.reduce((sum, item) => sum + item.size, 0);
res.json({ path: realPath, children: results, totalSize });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
function scanDirectory(dirPath, depthLimit, currentDepth) {
const results = [];
let entries;
try {
entries = fs.readdirSync(dirPath, { withFileTypes: true });
} catch {
return results;
}
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
try {
if (entry.isSymbolicLink()) continue;
if (entry.isDirectory()) {
let size = 0;
let children = [];
if (currentDepth < depthLimit) {
children = scanDirectory(fullPath, depthLimit, currentDepth + 1);
size = children.reduce((sum, child) => sum + child.size, 0);
} else {
try {
const duOutput = execSync(
`du -sk "${fullPath}" 2>/dev/null || echo "0"`,
{ timeout: 5000 }
).toString().trim();
const match = duOutput.match(/^(\d+)/);
size = match ? parseInt(match[1]) * 1024 : 0;
} catch {
size = 0;
}
}
children.sort((a, b) => b.size - a.size);
results.push({
name: entry.name,
path: fullPath,
size,
isDirectory: true,
children,
});
} else {
const stats = fs.statSync(fullPath);
results.push({
name: entry.name,
path: fullPath,
size: stats.size,
isDirectory: false,
children: [],
});
}
} catch {
// Skip inaccessible files
}
}
return results;
}
// Move items to Trash (macOS)
app.post('/api/trash', (req, res) => {
const { paths } = req.body;
if (!paths || !Array.isArray(paths) || paths.length === 0) {
return res.status(400).json({ error: 'No paths provided' });
}
// Safety: block critical system paths
const blocked = ['/', '/System', '/usr', '/bin', '/sbin', '/var', '/etc', '/tmp',
'/Applications', '/Library', os.homedir()];
const results = [];
for (const itemPath of paths) {
const resolved = path.resolve(itemPath);
if (blocked.includes(resolved)) {
results.push({ path: resolved, success: false, error: 'Protected system path' });
continue;
}
// Must be under home directory
if (!resolved.startsWith(os.homedir() + '/')) {
results.push({ path: resolved, success: false, error: 'Can only delete files under home directory' });
continue;
}
try {
// Use macOS trash via osascript (moves to Trash, recoverable)
execSync(
`osascript -e 'tell application "Finder" to delete POSIX file "${resolved}"'`,
{ timeout: 15000 }
);
results.push({ path: resolved, success: true });
} catch (err) {
results.push({ path: resolved, success: false, error: err.message });
}
}
const succeeded = results.filter(r => r.success).length;
const failed = results.filter(r => !r.success).length;
res.json({ results, succeeded, failed });
});
// Permanent delete
app.post('/api/delete', (req, res) => {
const { paths } = req.body;
if (!paths || !Array.isArray(paths) || paths.length === 0) {
return res.status(400).json({ error: 'No paths provided' });
}
const blocked = ['/', '/System', '/usr', '/bin', '/sbin', '/var', '/etc', '/tmp',
'/Applications', '/Library', os.homedir()];
const results = [];
for (const itemPath of paths) {
const resolved = path.resolve(itemPath);
if (blocked.includes(resolved)) {
results.push({ path: resolved, success: false, error: 'Protected system path' });
continue;
}
if (!resolved.startsWith(os.homedir() + '/')) {
results.push({ path: resolved, success: false, error: 'Can only delete files under home directory' });
continue;
}
try {
fs.rmSync(resolved, { recursive: true, force: true });
results.push({ path: resolved, success: true });
} catch (err) {
results.push({ path: resolved, success: false, error: err.message });
}
}
const succeeded = results.filter(r => r.success).length;
const failed = results.filter(r => !r.success).length;
res.json({ results, succeeded, failed });
});
app.listen(PORT, () => {
console.log(`Disk Analyzer running at http://localhost:${PORT}`);
});