-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
414 lines (346 loc) · 13.9 KB
/
Copy pathscript.js
File metadata and controls
414 lines (346 loc) · 13.9 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
document.addEventListener('DOMContentLoaded', () => {
// State
let processes = [];
let logs = [];
let filterUser = false;
let filterSystem = false;
let isPaused = false;
let searchQuery = '';
// Elements
const tableBody = document.querySelector('#process-table tbody');
const processCount = document.getElementById('process-count');
const logWindow = document.getElementById('log-window');
const searchInput = document.getElementById('process-search');
// Charts
const cpuCanvas = document.getElementById('cpu-chart');
const memCanvas = document.getElementById('mem-chart');
const forecastCpuCanvas = document.getElementById('forecast-cpu-chart');
const forecastMemCanvas = document.getElementById('forecast-mem-chart');
// Event Listeners
const btnClearHeader = document.getElementById('btn-clear-table-header');
if (btnClearHeader) {
btnClearHeader.addEventListener('click', () => {
tableBody.innerHTML = '';
processCount.textContent = '0 processes';
});
}
const btnDownloadHeader = document.getElementById('btn-download-logs-header');
if (btnDownloadHeader) {
btnDownloadHeader.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent bubbling if needed
downloadLogs();
});
}
// Dropdown Logic
const btnFilterDropdown = document.getElementById('btn-filter-dropdown');
const dropdownMenu = document.getElementById('filter-dropdown-menu');
const dropdownItems = document.querySelectorAll('.dropdown-item');
if (btnFilterDropdown && dropdownMenu) {
btnFilterDropdown.addEventListener('click', (e) => {
e.stopPropagation();
dropdownMenu.classList.toggle('show');
});
document.addEventListener('click', (e) => {
if (!dropdownMenu.contains(e.target) && !btnFilterDropdown.contains(e.target)) {
dropdownMenu.classList.remove('show');
}
});
dropdownItems.forEach(item => {
item.addEventListener('click', (e) => {
e.stopPropagation();
const filterType = item.dataset.filter;
if (filterType === 'user') {
filterUser = !filterUser;
// Mutually exclusive logic
if (filterUser && filterSystem) {
filterSystem = false;
}
} else if (filterType === 'system') {
filterSystem = !filterSystem;
// Mutually exclusive logic
if (filterSystem && filterUser) {
filterUser = false;
}
}
updateDropdownUI();
renderTable();
});
});
}
function updateDropdownUI() {
dropdownItems.forEach(item => {
const filterType = item.dataset.filter;
if (filterType === 'user') {
if (filterUser) item.classList.add('active');
else item.classList.remove('active');
} else if (filterType === 'system') {
if (filterSystem) item.classList.add('active');
else item.classList.remove('active');
}
});
}
searchInput.addEventListener('input', (e) => {
searchQuery = e.target.value.toLowerCase();
renderTable();
});
// Initial Load
// Clear logs on reload as requested
fetch('/clear-logs', { method: 'POST' })
.then(() => {
fetchData();
fetchLogs();
fetchForecast();
})
.catch(err => console.error('Error clearing logs:', err));
// Intervals
setInterval(fetchData, 2000);
setInterval(fetchLogs, 2000);
setInterval(fetchForecast, 5000);
// --- Data Fetching ---
async function fetchData() {
if (isPaused) return;
// Visual feedback for manual refresh
// const originalText = btnRefresh.textContent;
// if (originalText !== 'Refreshing...') {
// btnRefresh.textContent = 'Refreshing...';
// btnRefresh.disabled = true;
// }
try {
const res = await fetch('/live-process-data');
const data = await res.json();
processes = data;
renderTable();
} catch (err) {
console.error('Error fetching process data:', err);
} finally {
// Restore button state
// if (btnRefresh.textContent === 'Refreshing...') {
// btnRefresh.textContent = 'Refresh Now';
// btnRefresh.disabled = false;
// }
}
}
async function fetchLogs() {
try {
const res = await fetch('/log-stream');
const data = await res.json();
// Only update if new logs
if (JSON.stringify(data) !== JSON.stringify(logs)) {
logs = data;
renderLogs();
}
} catch (err) {
console.error('Error fetching logs:', err);
}
}
async function fetchForecast() {
try {
const res = await fetch('/forecast');
const data = await res.json();
if (data.realtime) {
drawChart(cpuCanvas, data.realtime.cpu, 'CPU %', '#3b82f6');
drawChart(memCanvas, data.realtime.memory, 'Memory %', '#8b5cf6');
}
if (data.forecast) {
drawChart(forecastCpuCanvas, data.forecast.cpu, 'Forecast CPU %', '#10b981');
drawChart(forecastMemCanvas, data.forecast.memory, 'Forecast Memory %', '#f59e0b');
}
} catch (err) {
console.error('Error fetching forecast:', err);
}
}
// --- Rendering ---
function renderTable() {
// Filter logic
let filtered = processes;
// If both unchecked, show all. If one checked, show that type.
// Note: "User" vs "System" is a bit ambiguous in cross-platform psutil.
// We'll use a heuristic: System usually has low PIDs or specific names,
// but for this demo, we might just filter by username if available,
// or just assume everything is "User" unless we have a flag.
// Since the backend doesn't explicitly send "type", let's use a simple heuristic:
// System: PID < 1000 (on Linux/Mac) or specific names.
// For Windows, it's harder. Let's just assume all are shown unless filtered.
// Actually, let's implement the requested logic:
// "Checkbox: show only user processes"
// "Checkbox: show only system processes"
// "If both are unchecked, show all processes"
// Search filter
if (searchQuery) {
filtered = filtered.filter(p =>
p.name.toLowerCase().includes(searchQuery)
);
}
// User/System filter
if (filterUser || filterSystem) {
filtered = filtered.filter(p => {
// Strict User App Filter
// User wants ONLY apps (Chrome, Antigravity, etc.) in User Processes
// Everything else goes to System
const name = p.name.toLowerCase();
const userAppKeywords = [
'chrome', 'firefox', 'edge', 'brave', 'opera', 'safari', // Browsers
'code', 'studio', 'sublime', 'notepad', 'word', 'excel', 'powerpoint', // Productivity
'discord', 'spotify', 'slack', 'teams', 'zoom', // Communication
'antigravity', 'python', 'node', 'java', 'ruby', 'go', // Dev tools (including this app)
'steam', 'epic', 'game', // Games
'vlc', 'obs', 'adobe' // Media
];
const isUserApp = userAppKeywords.some(keyword => name.includes(keyword));
// Debug log
console.log(`Process: ${name}, isUserApp: ${isUserApp}`);
// If filterUser is ON, we show ONLY User Apps
// If filterSystem is ON, we show ONLY System (Non-User Apps)
// If BOTH are ON, we show ALL (Union)
// If NEITHER are ON, we show ALL (Default)
if (!filterUser && !filterSystem) return true; // Show all
if (filterUser && filterSystem) return true; // Show all
if (filterUser && isUserApp) return true;
if (filterSystem && !isUserApp) return true;
return false;
});
}
processCount.textContent = `${filtered.length} processes`;
const html = filtered.map(p => {
const isAnomaly = p.anomaly_label === -1;
const rowClass = isAnomaly ? 'anomaly-row' : '';
const status = isAnomaly ? 'ANOMALY' : 'Normal';
return `
<tr class="${rowClass}">
<td>${p.pid}</td>
<td>${p.name}</td>
<td>${p.cpu_percent.toFixed(2)}%</td>
<td>${p.memory_percent.toFixed(2)}%</td>
<td>${p.num_threads}</td>
<td>${formatBytes(p.read_speed)}</td>
<td>${formatBytes(p.write_speed)}</td>
<td>${status}</td>
</tr>
`;
}).join('');
tableBody.innerHTML = html;
}
function renderLogs() {
const html = logs.map(log => {
return `
<div class="log-entry anomaly">
<div class="log-header">
<span class="log-time">${log.timestamp.split(' ')[1]}</span>
<span class="log-score">Score: ${log.anomaly_score.toFixed(2)}</span>
</div>
<div class="log-main">
<span class="log-name">${log.name}</span>
<span class="log-pid">PID: ${log.pid}</span>
</div>
<div class="log-details">${log.details}</div>
</div>
`;
}).join('');
logWindow.innerHTML = html;
}
// --- Charts (Canvas) ---
function drawChart(canvas, data, label, color) {
const ctx = canvas.getContext('2d');
const width = canvas.width = canvas.offsetWidth;
const height = canvas.height = canvas.offsetHeight;
// Clear
ctx.clearRect(0, 0, width, height);
// Config
const padding = 30; // Increased padding for labels
const chartWidth = width - padding * 2;
const chartHeight = height - padding * 2;
const stepX = chartWidth / (data.length - 1);
// Max value (Auto-scale for visibility, min 10%)
const maxData = Math.max(...data);
const maxY = Math.max(maxData * 1.2, 10);
// Draw Axes
ctx.beginPath();
ctx.strokeStyle = '#ccc';
ctx.lineWidth = 1;
// Y Axis
ctx.moveTo(padding, padding);
ctx.lineTo(padding, height - padding);
// X Axis
ctx.lineTo(width - padding, height - padding);
ctx.stroke();
// Axis Labels
ctx.fillStyle = '#fff';
ctx.font = '10px Inter';
ctx.textAlign = 'center';
ctx.fillText('Time', width / 2, height - 5);
ctx.save();
ctx.translate(10, height / 2);
ctx.rotate(-Math.PI / 2);
ctx.textAlign = 'center';
ctx.fillText('Usage %', 0, 0);
ctx.restore();
// Current Value (Top Right)
if (data.length > 0) {
const currentVal = data[data.length - 1];
ctx.fillStyle = color;
ctx.font = 'bold 14px Inter';
ctx.textAlign = 'right';
ctx.fillText(`${currentVal.toFixed(1)}%`, width - 10, 20);
}
// Draw Line
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = 2;
data.forEach((val, i) => {
const x = padding + i * stepX;
const y = height - padding - (val / maxY * chartHeight);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
// Draw Fill
ctx.lineTo(padding + (data.length - 1) * stepX, height - padding);
ctx.lineTo(padding, height - padding);
ctx.fillStyle = color + '20'; // Low opacity
ctx.fill();
// Draw Points
ctx.fillStyle = color;
data.forEach((val, i) => {
const x = padding + i * stepX;
const y = height - padding - (val / maxY * chartHeight);
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
});
}
// --- Utilities ---
function formatBytes(bytes, decimals = 2) {
if (!+bytes) return '0 B';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
}
function downloadLogs() {
if (logs.length === 0) {
alert("No logs to download");
return;
}
const headers = ["Timestamp", "PID", "Name", "Anomaly Score", "Details"];
const csvContent = [
headers.join(","),
...logs.map(log => [
log.timestamp,
log.pid,
log.name,
log.anomaly_score,
`"${log.details}"`
].join(","))
].join("\n");
const blob = new Blob([csvContent], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.setAttribute('hidden', '');
a.setAttribute('href', url);
a.setAttribute('download', 'anomaly_logs.csv');
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
});