-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.js
More file actions
284 lines (236 loc) · 10 KB
/
Copy pathapi.js
File metadata and controls
284 lines (236 loc) · 10 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
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { readAlertDatabase, getProduct } from './database.js';
import { recordSubscribe, getAnalytics } from './utils/analytics.js';
import { loadSettings, saveSettings } from './settings-store.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
function normalizeOrigin(origin) {
if (!origin || typeof origin !== 'string') return null;
try {
return new URL(origin).origin.toLowerCase();
} catch {
return origin.trim().toLowerCase().replace(/\/+$/, '');
}
}
export default class API {
constructor(port, options = {}) {
this.port = port;
this.sseClients = new Set(); // Track all SSE client state objects
this.corsEnabled = options.corsEnabled ?? true;
this.allowNoOrigin = options.allowNoOrigin ?? false;
this.domainWhitelist = new Set((options.domainWhitelist || [])
.map(normalizeOrigin)
.filter(Boolean));
this.app = express();
this.app.use(express.json());
this.app.use(express.static(path.join(__dirname, 'public'))); // Serve static files
this.app.use((req, res, next) => {
if (!this.corsEnabled) {
return next();
}
const requestOrigin = normalizeOrigin(req.headers.origin);
const hasWhitelist = this.domainWhitelist.size > 0;
const originAllowed = requestOrigin && this.domainWhitelist.has(requestOrigin);
const noOriginAllowed = !requestOrigin && this.allowNoOrigin;
res.setHeader('Vary', 'Origin');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
const requestedHeaders = req.headers['access-control-request-headers'];
if (typeof requestedHeaders === 'string' && requestedHeaders.trim()) {
res.setHeader('Access-Control-Allow-Headers', requestedHeaders);
res.setHeader('Vary', 'Origin, Access-Control-Request-Headers');
} else {
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
res.setHeader('Access-Control-Max-Age', '86400');
if (requestOrigin && (!hasWhitelist || originAllowed)) {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
}
if (req.method === 'OPTIONS') {
if (hasWhitelist && !originAllowed && !noOriginAllowed) {
return res.status(403).json({ error: 'Origin not allowed.' });
}
return res.sendStatus(204);
}
if (hasWhitelist && !originAllowed && !noOriginAllowed) {
return res.status(403).json({ error: 'Origin not allowed.' });
}
next();
});
// Status endpoint
this.app.get('/', (req, res) => {
res.json({ status: 'ok' });
});
// Dashboard endpoint
this.app.get('/dashboard', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Endpoint to get all active alerts
this.app.get('/alerts', (req, res) => {
// Return all alerts from the database
res.json({ alerts: readAlertDatabase() });
});
// Endpoint to subscribe to SSE stream
this.app.get('/subscribe', (req, res) => {
const toLog = req.query.log === 'true' ? true : false; // Default to false if not specified
console.log('Subscribe hit; log subscribe event:', toLog);
// Set up SSE headers
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
// Flush headers early so proxies and browsers treat this as a live stream immediately
if (typeof res.flushHeaders === 'function') {
res.flushHeaders();
}
// Instruct EventSource clients how quickly they should retry after disconnect
res.write('retry: 5000\n\n');
const heartbeatIntervalMs = 25000;
const client = {
res,
heartbeat: null
};
const cleanupClient = () => {
if (client.heartbeat) {
clearInterval(client.heartbeat);
client.heartbeat = null;
}
this.sseClients.delete(client);
};
// Add this client to the set
this.sseClients.add(client);
// Keep the connection alive with a comment
res.write(':connected\n\n');
// Keep stream alive through proxies/load balancers that close idle HTTP connections
client.heartbeat = setInterval(() => {
if (res.writableEnded || res.destroyed) {
cleanupClient();
return;
}
try {
res.write(`:heartbeat ${Date.now()}\n\n`);
} catch {
cleanupClient();
}
}, heartbeatIntervalMs);
// Record successful subscribe event
if (toLog) recordSubscribe();
// Remove client on disconnect
req.on('close', cleanupClient);
res.on('close', cleanupClient);
res.on('error', cleanupClient);
});
this.app.get('/product/:code', (req, res) => {
const code = req.params.code;
switch (code) {
case 'COD':
try {
const productData = getProduct(code.toLowerCase());
res.json(productData);
} catch (err) {
res.status(404).json({ error: err.message });
}
break;
default:
res.status(404).json({ error: 'Product not supported or unavailable.' });
}
});
// Endpoint to get analytics data (subscribe events by day for last 30 days)
this.app.get('/analytics', (req, res) => {
res.json(getAnalytics());
});
// Endpoint to get current connections
this.app.get('/connections', (req, res) => {
res.json({ connections: this.sseClients.size });
});
// Endpoint to retrieve the announcement data
this.app.get('/announcement', (req, res) => {
const announcementPath = path.join(__dirname, 'announcement.json');
res.sendFile(announcementPath, err => {
if (err) {
console.error('Error sending announcement.json:', err);
res.status(500).json({ error: 'Failed to load announcement.' });
}
});
});
// Endpoint to load settings given a passphrase
this.app.get('/settings/:pass', (req, res) => {
const settings = loadSettings(req.params.pass);
if (!settings) {
return res.status(404).json({ error: 'Settings not found' });
}
res.json(settings);
});
// Endpoint to save settings given a passphrase
this.app.post('/settings/:pass', (req, res) => {
const passphrase = req.params.pass;
const settings = req.body;
if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
return res.status(400).json({ error: 'Settings must be a JSON object' });
}
try {
const success = saveSettings(passphrase, settings);
if (!success) {
return res.status(400).json({ error: 'Invalid passphrase' });
}
} catch (err) {
return res.status(500).json({ error: 'Failed to save settings' });
}
res.json({ success: true });
});
this.app.listen(this.port, () => {
console.log(`API server running on http://localhost:${this.port}`);
});
}
// Function that triggers a SSE:NEW event
// Indicates a new alert has been added to the database
triggerNewAlertEvent(alert) {
if (!alert) {
console.warn('API: triggerNewAlertEvent called with no alert data');
return;
}
this._broadcastEvent('NEW', alert);
}
// Function that triggers a SSE:UPDATE event
// Indicates the database has changed but no new alert has been added
triggerUpdateAlertEvent(alert) {
if (!alert) {
console.warn('API: triggerUpdateAlertEvent called with no alert data');
return;
}
this._broadcastEvent('UPDATE', alert);
}
_broadcastEvent(eventType, data) {
if (!data) {
console.error(`API: Cannot broadcast ${eventType} event with null/undefined data`);
return;
}
let jsonData;
try {
jsonData = JSON.stringify(data);
} catch (err) {
console.error(`API: Failed to stringify ${eventType} event data:`, err.message);
return;
}
const message = `event: ${eventType}\ndata: ${jsonData}\n\n`;
// Send to all connected SSE clients
let successCount = 0;
this.sseClients.forEach(client => {
const response = client.res;
if (!response || response.writableEnded || response.destroyed) {
this.sseClients.delete(client);
return;
}
try {
response.write(message);
successCount++;
} catch (err) {
// Client disconnected, remove it
this.sseClients.delete(client);
}
});
if (successCount > 0) {
console.log(`API: Broadcasted ${eventType} event to ${successCount} client(s)`);
}
}
}