-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
492 lines (440 loc) · 15.7 KB
/
Copy pathserver.ts
File metadata and controls
492 lines (440 loc) · 15.7 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/**
* @license
* SPDX-License-Identifier: Apache-2.0
*/
import express from 'express';
import path from 'path';
import fs from 'fs';
import http from 'http';
import { exec } from 'child_process';
import { simulator } from './src/utils/debianSimulator.js';
const STATE_PORT_FILE = '/tmp/spaceguard.port';
// Helper to check if a daemon is already running
async function checkDaemonRunning(): Promise<string | null> {
if (!fs.existsSync(STATE_PORT_FILE)) return null;
try {
const url = fs.readFileSync(STATE_PORT_FILE, 'utf8').trim();
return new Promise((resolve) => {
const req = http.get(`${url}/api/status`, { timeout: 1000 }, (res) => {
if (res.statusCode === 200) resolve(url);
else resolve(null);
});
req.on('error', () => resolve(null));
req.end();
});
} catch {
return null;
}
}
// Open default browser helper
function openBrowser(url: string) {
console.log(`[SpaceGuard] Otwieranie interfejsu GUI w przeglądarce: ${url}`);
const startCmd = process.platform === 'darwin'
? `open "${url}"`
: process.platform === 'win32'
? `start "${url}"`
: `xdg-open "${url}" || sensible-browser "${url}" || x-www-browser "${url}"`;
exec(startCmd, (err) => {
if (err) {
console.log(`[SpaceGuard] Aby otworzyć interfejs GUI, wejdź w przeglądarce pod adres: ${url}`);
}
});
}
// CLI Arg handler
async function handleCLIArgs(): Promise<boolean> {
const args = process.argv.slice(2);
if (args.length === 0) return false;
const command = args[0].toLowerCase();
if (command === '--help' || command === '-h' || command === 'help') {
console.log(`
🛡️ SpaceGuard v1.2.0 - Standalone Disk Space Optimizer & Live System Audit Daemon
SKŁADNIA:
spaceguard [KOMENDA] [OPCJE]
KOMENDY:
open, gui Otwiera interfejs graficzny SpaceGuard w domyślnej przeglądarce
status Wyświetla bieżący status dysku oraz zużycie pamięci demona
scan Uruchamia głęboki skan struktury katalogów i pakietów dpkg/brew
clean Opróżnia kosz oraz archiwum podrzędne pakietów (.deb/.dmg)
daemon, start Uruchamia usługę demona w tle (obsługuje automatyczny port fallback)
--version, -v Wyświetla zainstalowaną wersję aplikacji SpaceGuard
--help, -h Wyświetla tę pomoc
PRZYKŁADY:
spaceguard open # Otwiera GUI
spaceguard status # Status z wiersza poleceń
spaceguard clean # Szybkie czyszczenie w terminalu
`);
process.exit(0);
}
if (command === '--version' || command === '-v' || command === 'version') {
console.log('SpaceGuard v1.2.0 (standalone daemon & storage analyzer)');
process.exit(0);
}
const runningUrl = await checkDaemonRunning();
if (command === 'open' || command === 'gui') {
if (runningUrl) {
openBrowser(runningUrl);
} else {
console.log('[SpaceGuard] Usługa demona nie jest jeszcze uruchomiona. Uruchamianie nowego demona...');
return false; // Continues to start server
}
process.exit(0);
}
if (command === 'status' || command === 'scan' || command === 'clean') {
if (runningUrl) {
try {
const endpoint = command === 'status' ? '/api/status' : command === 'scan' ? '/api/scan' : '/api/clean';
const method = command === 'status' ? 'GET' : 'POST';
const req = http.request(`${runningUrl}${endpoint}`, { method }, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
const parsed = JSON.parse(data);
if (parsed.output) {
console.log(parsed.output);
} else {
console.log(`[SpaceGuard Status] Zajęte miejsce: ${parsed.disk.usedGb} GB / ${parsed.disk.totalGb} GB (${Math.round((parsed.disk.usedGb / parsed.disk.totalGb) * 100)}%)`);
console.log(`Zainstalowane pakiety: ${parsed.packagesCount} | Kosz: ${parsed.disk.trashSizeMb} MB | APT Cache: ${parsed.disk.cacheSizeMb} MB`);
}
} catch {
console.log(data);
}
process.exit(0);
});
});
req.on('error', (err) => {
console.error(`[SpaceGuard CLI Error] Błąd połączenia z demonem: ${err.message}`);
process.exit(1);
});
req.end();
return true;
} catch (e: any) {
console.error(`[SpaceGuard CLI Error] ${e.message}`);
process.exit(1);
}
} else {
// Direct local execution if daemon is not running
const output = simulator.executeCLI(command);
console.log(output);
process.exit(0);
}
}
return false;
}
async function startServer() {
const handled = await handleCLIArgs();
if (handled) return;
// Check if daemon is ALREADY running on system
const runningUrl = await checkDaemonRunning();
if (runningUrl) {
console.log(`[SpaceGuard Daemon] Demon już działa w tle na porcie: ${runningUrl}`);
if (process.argv.includes('--open') || process.argv.includes('open')) {
openBrowser(runningUrl);
} else {
console.log(`[SpaceGuard Daemon] Użyj 'spaceguard open' aby otworzyć interfejs GUI.`);
}
process.exit(0);
}
const app = express();
let preferredPort = parseInt(process.env.PORT || '3000', 10);
app.use(express.json());
// API Route: Get system disk and indicator tray status
app.get('/api/status', (req, res) => {
try {
res.json({
disk: simulator.getDiskStatus(),
packagesCount: simulator.getPackages().filter(p => p.status === 'installed').length
});
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Get full packages list
app.get('/api/packages', (req, res) => {
try {
res.json(simulator.getPackages());
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Get Disk Space Treemap and File Mapping
app.get('/api/diskmap', (req, res) => {
try {
const mode = (req.query.mode as 'folders' | 'applications') || 'applications';
res.json(simulator.getDiskMap(mode));
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Get a specific package's metadata and connections
app.get('/api/packages/:name', (req, res) => {
try {
const pkg = simulator.getPackage(req.params.name);
if (!pkg) {
return res.status(404).json({ error: 'Pakiet nie odnaleziony.' });
}
res.json(pkg);
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Install a simulated Debian package
app.post('/api/packages/install', (req, res) => {
try {
const { name, installer, hasSudo, method, sourceUrl } = req.body;
if (!name) {
return res.status(400).json({ error: 'Brak nazwy pakietu.' });
}
const success = simulator.installPackage(
name,
installer || 'root',
hasSudo !== undefined ? hasSudo : true,
method || 'apt',
sourceUrl || ''
);
if (!success) {
return res.status(400).json({ error: 'Instalacja nie powiodła się.' });
}
res.json({ success: true, disk: simulator.getDiskStatus() });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Add simulated custom wget/curl/zip file footprint
app.post('/api/packages/custom', (req, res) => {
try {
const { name, sizeMb, url, installer, hasSudo, method, createdFiles, collaboratingWith } = req.body;
if (!name || !sizeMb) {
return res.status(400).json({ error: 'Nazwa i rozmiar (MB) są wymagane.' });
}
const pkg = simulator.addCustomDownload({
name,
sizeMb: parseFloat(sizeMb),
url: url || `https://custom-dl.org/${name}`,
installer: installer || 'kali',
hasSudo: hasSudo !== undefined ? hasSudo : false,
method: method || 'wget',
createdFiles,
collaboratingWith
});
res.json({ success: true, pkg, disk: simulator.getDiskStatus() });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Remove/Free a simulated package
app.post('/api/packages/remove', (req, res) => {
try {
const { name } = req.body;
if (!name) {
return res.status(400).json({ error: 'Brak nazwy pakietu.' });
}
const result = simulator.removePackage(name);
if (!result.success) {
return res.status(400).json({ error: result.reason });
}
res.json({ success: true, freedMb: result.freedMb, disk: simulator.getDiskStatus() });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Run full scan and synchronize metrics
app.post('/api/scan', (req, res) => {
try {
const output = simulator.executeCLI('scan');
res.json({ output, disk: simulator.getDiskStatus() });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Free target space recommendations
app.get('/api/recommendations', (req, res) => {
try {
const targetGb = parseFloat(req.query.target as string || '2.0');
const recs = simulator.generateRecommendations(targetGb);
res.json(recs);
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Wipe system cache and garbage-collect
app.post('/api/clean', (req, res) => {
try {
const output = simulator.executeCLI('clean');
res.json({ output, disk: simulator.getDiskStatus() });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Get Docker and Podman resources
app.get('/api/containers/resources', (req, res) => {
try {
res.json({
dockerImages: simulator.getDockerImages(),
dockerContainers: simulator.getDockerContainers(),
podmanImages: simulator.getPodmanImages(),
podmanContainers: simulator.getPodmanContainers(),
disk: simulator.getDiskStatus()
});
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Remove a resource
app.post('/api/containers/remove', (req, res) => {
try {
const { engine, type, id } = req.body;
if (!engine || !type || !id) {
return res.status(400).json({ error: 'engine, type i id są wymagane.' });
}
let success = false;
if (engine === 'docker') {
if (type === 'image') success = simulator.removeDockerImage(id);
else if (type === 'container') success = simulator.removeDockerContainer(id);
} else if (engine === 'podman') {
if (type === 'image') success = simulator.removePodmanImage(id);
else if (type === 'container') success = simulator.removePodmanContainer(id);
}
if (!success) {
return res.status(400).json({ error: 'Nie udało się usunąć zasobu.' });
}
res.json({ success: true, disk: simulator.getDiskStatus() });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Prune an engine
app.post('/api/containers/prune', (req, res) => {
try {
const { engine } = req.body;
if (!engine) {
return res.status(400).json({ error: 'engine jest wymagany.' });
}
let result;
if (engine === 'docker') {
result = simulator.pruneDocker();
} else if (engine === 'podman') {
result = simulator.prunePodman();
} else {
return res.status(400).json({ error: 'Nieobsługiwany silnik.' });
}
res.json({
success: true,
freedMb: result.freedMb,
deletedContainers: result.deletedContainers,
deletedImages: result.deletedImages,
disk: simulator.getDiskStatus()
});
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Execute interactive CLI commands from UI Terminal
app.post('/api/cli', (req, res) => {
try {
const { command } = req.body;
if (command === undefined) {
return res.status(400).json({ error: 'Brak polecenia.' });
}
const output = simulator.executeCLI(command);
res.json({ output, disk: simulator.getDiskStatus() });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Reset simulated state
app.post('/api/reset', (req, res) => {
try {
simulator.reset();
res.json({ success: true, disk: simulator.getDiskStatus() });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Software Update Check & Apply
let appVersion = '1.2.0';
const latestRelease = {
version: '1.2.5',
releaseDate: '2026-07-22',
changelog: [
'Enhanced Docker & Podman layer disk space reclamation',
'Optimized D3 dependency graph rendering performance',
'Added MacOS and multi-OS storage analyzer compatibility hooks',
'Updated security audit rules & orphan package heuristics'
]
};
app.get('/api/update/check', (req, res) => {
try {
const hasUpdate = appVersion !== latestRelease.version;
res.json({
currentVersion: appVersion,
latestVersion: latestRelease.version,
hasUpdate,
release: latestRelease
});
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
app.post('/api/update/apply', (req, res) => {
try {
appVersion = latestRelease.version;
res.json({
success: true,
version: appVersion,
message: 'SpaceGuard updated successfully. All user settings, logs, and state preserved.'
});
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API Route: Simulate external background installation / download
app.post('/api/simulate-external', (req, res) => {
try {
const result = simulator.simulateExternalInstallation();
res.json({ success: true, item: result, disk: simulator.getDiskStatus() });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// Vite middleware for development or Static Assets for production
if (process.env.NODE_ENV !== 'production') {
const { createServer: createViteServer } = await import('vite');
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
// Resilient listener with EADDRINUSE auto port fallback
const listenWithFallback = (port: number) => {
const server = app.listen(port, '0.0.0.0', () => {
const activeUrl = `http://localhost:${port}`;
console.log(`[SpaceGuard Backend Server] Aktywny pod adresem: ${activeUrl}`);
try {
fs.writeFileSync(STATE_PORT_FILE, activeUrl, 'utf8');
} catch {}
if (process.argv.includes('--open') || process.argv.includes('open')) {
openBrowser(activeUrl);
}
});
server.on('error', (err: any) => {
if (err.code === 'EADDRINUSE') {
console.warn(`[SpaceGuard Warn] Port ${port} jest już zajęty przez inną usługę. Wybieranie wolnego portu zapasowego...`);
// Retry on port + 1 or 0 (random free OS port if > 3010)
const nextPort = port >= 3010 ? 0 : port + 1;
setTimeout(() => listenWithFallback(nextPort), 200);
} else {
console.error(`[SpaceGuard Error] Błąd serwera: ${err.message}`);
}
});
};
listenWithFallback(preferredPort);
}
startServer();