-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
354 lines (315 loc) · 11.8 KB
/
main.js
File metadata and controls
354 lines (315 loc) · 11.8 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
import crypto from 'crypto';
import axios from 'axios';
import sqlite3 from 'sqlite3';
import { createCanvas } from 'canvas';
import { app, BrowserWindow, ipcMain, Notification, Tray, nativeImage, Menu } from 'electron';
import path from 'path';
import { promisify } from 'util';
const dbPath = path.join(app.getPath('userData'), 'api_monitor.db');
const db = new sqlite3.Database(dbPath);
// Promisify database methods
const dbRun = promisify(db.run.bind(db));
const dbGet = promisify(db.get.bind(db));
const dbAll = promisify(db.all.bind(db));
// Initialize database tables
const initializeDatabase = async () => {
// Drop existing tables and recreate with correct schema
await dbRun(`DROP TABLE IF EXISTS requests`);
await dbRun(`DROP TABLE IF EXISTS request_profiles`);
await dbRun(`
CREATE TABLE request_profiles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL,
method TEXT NOT NULL,
headers TEXT DEFAULT '{}',
body TEXT DEFAULT '{}',
preprocessing TEXT DEFAULT '',
call_count INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_updated DATETIME DEFAULT CURRENT_TIMESTAMP,
interval_seconds INTEGER DEFAULT 10
)
`);
await dbRun(`
CREATE TABLE requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
profile_id INTEGER,
raw_data TEXT,
processed_data TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
success INTEGER DEFAULT 1,
status INTEGER,
hasChanged INTEGER DEFAULT 0,
error TEXT,
FOREIGN KEY (profile_id) REFERENCES request_profiles (id)
)
`);
};
// Initialize database on startup
initializeDatabase().catch(console.error);
let mainWindow, tray, apiInterval, notificationCount = 0;
const hash = data => crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');
const updateOrCreateProfile = async config => {
if (!config) return;
if (config._id) {
await dbRun(
`UPDATE request_profiles SET url = ?, method = ?, headers = ?, body = ?, preprocessing = ?, interval_seconds = ?, last_updated = CURRENT_TIMESTAMP WHERE id = ?`,
[config.url, config.method, JSON.stringify(config.headers || {}), config.body, config.preprocessing || '', config.interval || 10, parseInt(config._id)]
);
return { id: config._id };
}
const stmt = await dbRun(
`INSERT INTO request_profiles (url, method, headers, body, preprocessing, interval_seconds) VALUES (?, ?, ?, ?, ?, ?) returning id`,
[config.url, config.method, JSON.stringify(config.headers || {}), config.body, config.preprocessing || '', config.interval || 10]
);
return { success: true }
};
const executePreprocessing = (code, data) => {
try {
return new Function('data', code)(data);
} catch (e) {
throw new Error(`Preprocessing: ${e.message}`);
}
};
const createTrayIcon = () => {
const canvas = createCanvas(16, 16);
const context = canvas.getContext('2d');
context.fillStyle = '#ef4444';
context.beginPath();
context.arc(8, 8, 7, 0, 2 * Math.PI);
context.fill();
if (notificationCount) {
context.fillStyle = 'white';
context.font = '10px Arial';
context.textAlign = 'center';
context.fillText(notificationCount > 99 ? '99+' : notificationCount.toString(), 8, 11);
}
return nativeImage.createFromBuffer(canvas.toBuffer());
};
const setupTray = () => {
if (!tray) {
tray = new Tray(createTrayIcon());
tray.setToolTip('API Monitor');
tray.on('click', () => mainWindow.show());
} else {
tray.setImage(createTrayIcon());
}
tray.setContextMenu(Menu.buildFromTemplate([
{ label: `Notifications: ${notificationCount}`, enabled: false },
{ type: 'separator' },
{ label: 'Clear', enabled: !!notificationCount, click: () => { notificationCount = 0; setupTray(); mainWindow.webContents.send('notification-count-updated', 0); } },
{ label: 'Show', click: () => mainWindow.show() },
{ type: 'separator' },
{ label: 'Quit', click: () => app.quit() }
]));
};
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
show: false,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.join(process.cwd(), 'preload.js'),
}
});
mainWindow.loadFile('./dist/index.html');
mainWindow.once('ready-to-show', () => { mainWindow.show(); setupTray(); });
mainWindow.on('close', e => {
if (!app.isQuiting) {
e.preventDefault();
mainWindow.hide();
}
});
}
app.whenReady().then(createWindow);
app.on('before-quit', () => app.isQuiting = true);
app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } });
app.on('activate', () => BrowserWindow.getAllWindows().length === 0 ? createWindow() : mainWindow.show());
const makeApiCall = async config => {
try {
let bodyData = null;
if (config.body && ['POST', 'PUT', 'PATCH'].includes(config.method)) {
bodyData = typeof config.body === 'string' ? JSON.parse(config.body) : config.body;
}
const res = await axios({
method: config.method || 'GET',
url: config.url,
headers: config.headers || {},
data: bodyData,
timeout: 30000
});
const result = {
success: true,
status: res.status,
statusText: res.statusText,
data: res.data,
timestamp: new Date().toISOString()
};
let processed_data = null;
if (config.preprocessing) {
try {
processed_data = executePreprocessing(config.preprocessing, res.data);
result.processedData = processed_data;
result.originalData = res.data;
} catch (e) {
result.preprocessingError = e.message;
}
}
let has_changed = true;
if (config._id) {
const lastRequests = await dbAll(
`SELECT * FROM requests WHERE profile_id = ? ORDER BY timestamp DESC LIMIT 1`,
[parseInt(config._id)]
);
if (lastRequests.length > 0) {
const lastData = lastRequests[0].processed_data ? JSON.parse(lastRequests[0].processed_data) : JSON.parse(lastRequests[0].raw_data || '{}');
const currentData = processed_data || res.data;
has_changed = hash(currentData) !== hash(lastData);
}
if (has_changed) {
await dbRun(
`INSERT INTO requests (profile_id, raw_data, processed_data, success, status, hasChanged) VALUES (?, ?, ?, ?, ?, ?)`,
[parseInt(config._id), JSON.stringify(res.data), processed_data ? JSON.stringify(processed_data) : null, 1, res.status, 1]
);
await dbRun(`UPDATE request_profiles SET call_count = call_count + 1, last_updated = CURRENT_TIMESTAMP WHERE id = ?`, [parseInt(config._id)]);
if (config.checkChanges && Notification.isSupported()) {
notificationCount++;
setupTray();
mainWindow.webContents.send('notification-count-updated', notificationCount);
const n = new Notification({
title: 'API Monitor - Data Changed',
body: `${config.method} ${config.url} - Response changed`,
timeoutType: 'never',
silent: false
});
n.show();
n.on('click', () => mainWindow.show());
}
}
result.hasChanged = has_changed;
const profile = await dbGet(`SELECT call_count FROM request_profiles WHERE id = ?`, [parseInt(config._id)]);
result.callCount = profile ? profile.call_count : 1;
}
return result;
} catch (e) {
if (config._id) {
await dbRun(
`INSERT INTO requests (profile_id, success, status, error, hasChanged) VALUES (?, ?, ?, ?, ?)`,
[parseInt(config._id), 0, e.response?.status || null, e.message, 1]
).catch(() => {});
}
return {
success: false,
error: e.message,
status: e.response?.status,
timestamp: new Date().toISOString(),
hasChanged: true,
callCount: 1
};
}
};
// IPC handlers
ipcMain.handle('make-api-call', (_, config) => makeApiCall(config));
ipcMain.handle('start-monitoring', (_, config) => {
clearInterval(apiInterval);
apiInterval = setInterval(async () => {
const result = await makeApiCall({ ...config, checkChanges: true });
mainWindow.webContents.send('api-response', result);
}, config.interval * 1000);
return { success: true };
});
ipcMain.handle('stop-monitoring', () => {
clearInterval(apiInterval);
apiInterval = null;
return { success: true };
});
ipcMain.handle('get-notification-count', () => notificationCount);
ipcMain.handle('clear-notifications', () => {
notificationCount = 0;
setupTray();
return { success: true };
});
ipcMain.handle('get-db-stats', async () => {
try {
const profiles = await dbAll(`SELECT * FROM request_profiles ORDER BY last_updated DESC`);
return profiles.map(row => ({
...row,
_id: row.id.toString(),
headers: JSON.parse(row.headers || '{}'),
body: row.body || ''
}));
} catch (e) {
console.error('DB error:', e);
return [];
}
});
ipcMain.handle('save-request-profile', (_, config) => updateOrCreateProfile(config));
ipcMain.handle('load-profiles', async () => {
try {
const profiles = await dbAll(`SELECT * FROM request_profiles ORDER BY last_updated DESC`);
return profiles.map(row => ({
...row,
_id: row.id.toString(),
headers: JSON.parse(row.headers || '{}'),
body: row.body || ''
}));
} catch (e) {
console.error('Load profiles error:', e);
return [];
}
});
ipcMain.handle('load-profile', async (_, profileId) => {
try {
const profile = await dbGet(`SELECT * FROM request_profiles WHERE id = ?`, [parseInt(profileId)]);
if (profile) {
return {
...profile,
_id: profile.id.toString(),
headers: JSON.parse(profile.headers || '{}'),
body: JSON.parse(profile.body || '{}')
};
}
return null;
} catch (e) {
console.error('Load profile error:', e);
return null;
}
});
ipcMain.handle('delete-profile', async (_, profileId) => {
try {
const id = parseInt(profileId);
await dbRun(`DELETE FROM requests WHERE profile_id = ?`, [id]);
await dbRun(`DELETE FROM request_profiles WHERE id = ?`, [id]);
return { success: true };
} catch (e) {
console.error('Delete profile error:', e);
return { success: false };
}
});
ipcMain.handle('load-request-history', async (_, profileId) => {
try {
const requests = await dbAll(
`SELECT * FROM requests WHERE profile_id = ? ORDER BY timestamp DESC LIMIT 5`,
[parseInt(profileId)]
);
return requests.map(row => ({
...row,
raw_data: row.raw_data ? JSON.parse(row.raw_data) : null,
processed_data: row.processed_data ? JSON.parse(row.processed_data) : null
}));
} catch (e) {
console.error('Load history error:', e);
return [];
}
});
process.on('exit', () => {
try {
db.close();
} catch (e) { }
});
process.on('SIGINT', () => {
db.close();
process.exit();
});