-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
401 lines (336 loc) Β· 11.5 KB
/
Copy pathserver.js
File metadata and controls
401 lines (336 loc) Β· 11.5 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
import "dotenv/config";
import express from "express";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import webpush from "web-push";
import { WebSocketServer } from "ws";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PORT = process.env.PORT || 3000;
const RECORDINGS_DIR = path.join(__dirname, "public/recordings");
// Create directories if they don't exist
if (!fs.existsSync(path.join(__dirname, "public"))) {
fs.mkdirSync(path.join(__dirname, "public"), { recursive: true });
}
if (!fs.existsSync(RECORDINGS_DIR)) {
fs.mkdirSync(RECORDINGS_DIR, { recursive: true });
}
// Web Push configuration
let webPushConfigured = false;
if (process.env.VAPID_PUBLIC_KEY && process.env.VAPID_PRIVATE_KEY && process.env.VAPID_EMAIL) {
try {
webpush.setVapidDetails(
`mailto:${process.env.VAPID_EMAIL}`,
process.env.VAPID_PUBLIC_KEY,
process.env.VAPID_PRIVATE_KEY
);
webPushConfigured = true;
console.log('β
Web Push configured successfully');
} catch (err) {
console.error('β Web Push configuration failed:', err.message);
}
} else {
console.log('β οΈ VAPID keys not configured. Push notifications disabled.');
}
const app = express();
const server = app.listen(PORT, () => {
console.log(`πΉ Watchtower Live server running on http://localhost:${PORT}`);
console.log(`π Recordings saved to: ${RECORDINGS_DIR}`);
});
const wss = new WebSocketServer({ server });
let showBoxes = true;
let subscribers = new Set(); // Store push notification subscriptions
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json({ limit: '10mb' })); // Increase limit for image data
// Serve the main page
app.get("/", (req, res) => {
fs.readFile(path.join(__dirname, "index.html"), 'utf8', (err, data) => {
if (err) {
return res.status(500).send('Error loading page');
}
// Replace the VAPID key placeholder with the actual key
const updatedHtml = data.replace(
'VAPID_PUBLIC_KEY_PLACEHOLDER',
process.env.VAPID_PUBLIC_KEY || ''
);
res.send(updatedHtml);
});
});
// Get VAPID public key
app.get("/vapid-public-key", (req, res) => {
res.json({ publicKey: process.env.VAPID_PUBLIC_KEY || '' });
});
// Toggle detection boxes
app.get("/toggle-boxes", (req, res) => {
showBoxes = !showBoxes;
console.log(`π Detection boxes: ${showBoxes ? 'ON' : 'OFF'}`);
res.json({ showBoxes });
});
// Get recordings list for gallery
app.get("/recordings.json", (req, res) => {
fs.readdir(RECORDINGS_DIR, (err, files) => {
if (err) {
console.error("Error reading recordings directory:", err);
return res.json([]);
}
const jpgs = files
.filter(f => f.endsWith(".jpg"))
.sort((a, b) => {
// Sort by timestamp in filename (newest first)
const timeA = parseInt(a.split('-')[1]?.split('.')[0] || '0');
const timeB = parseInt(b.split('-')[1]?.split('.')[0] || '0');
return timeB - timeA;
});
res.json(jpgs);
});
});
// Delete specific image
app.delete("/delete-image/:filename", (req, res) => {
const filename = req.params.filename;
const filePath = path.join(RECORDINGS_DIR, filename);
// Security check - ensure filename is safe
if (filename.includes('..') || !filename.endsWith('.jpg')) {
return res.status(400).json({ error: "Invalid filename" });
}
fs.unlink(filePath, (err) => {
if (err) {
console.error("Error deleting file:", err);
return res.status(500).json({ error: "Failed to delete file" });
}
console.log(`ποΈ Deleted: ${filename}`);
res.json({ success: true });
});
});
// Clear all images
app.post("/clear-all", (req, res) => {
fs.readdir(RECORDINGS_DIR, (err, files) => {
if (err) {
console.error("Error reading recordings directory:", err);
return res.status(500).json({ error: "Failed to read directory" });
}
const jpgFiles = files.filter(f => f.endsWith('.jpg'));
if (jpgFiles.length === 0) {
return res.json({ success: true, deleted: 0 });
}
let deletedCount = 0;
let processedCount = 0;
let responseSent = false;
jpgFiles.forEach(file => {
fs.unlink(path.join(RECORDINGS_DIR, file), (err) => {
if (!err) deletedCount++;
processedCount++;
// Check if all files have been processed and response hasn't been sent
if (processedCount === jpgFiles.length && !responseSent) {
responseSent = true;
console.log(`ποΈ Deleted ${deletedCount} images`);
res.json({ success: true, deleted: deletedCount });
}
});
});
});
});
// Push notification subscription
app.post("/subscribe", (req, res) => {
try {
const subscription = req.body;
console.log('π± New subscription received:', JSON.stringify(subscription, null, 2));
if (!subscription || !subscription.endpoint) {
return res.status(400).json({ error: 'Invalid subscription' });
}
subscribers.add(JSON.stringify(subscription));
console.log(`π Total subscribers: ${subscribers.size}`);
res.status(201).json({ success: true, message: 'Subscription saved' });
} catch (err) {
console.error('β Subscription error:', err);
res.status(500).json({ error: 'Failed to save subscription' });
}
});
// Send test notification
app.post("/test-notification", (req, res) => {
console.log('π§ͺ Test notification requested');
if (!webPushConfigured) {
console.log('β Web Push not configured');
return res.status(500).json({ error: 'Web Push not configured' });
}
if (subscribers.size === 0) {
console.log('β No subscribers found');
return res.status(400).json({ error: 'No subscribers found' });
}
const result = sendNotification("π§ͺ Test Notification", "This is a test from Watchtower Live!");
if (result) {
res.json({ success: true, message: 'Test notification sent' });
} else {
res.status(500).json({ error: 'Failed to send test notification' });
}
});
// Object detected notification trigger
app.post("/object-detected", (req, res) => {
const { objects } = req.body;
const timestamp = new Date().toLocaleString();
const objectList = objects || 'Unknown object';
sendNotification(
`π ${objectList} Detected!`,
`${objectList} detected by Watchtower Live at ${timestamp}`
);
res.json({ success: true });
});
// Person detected notification trigger (legacy support)
app.post("/person-detected", (req, res) => {
const timestamp = new Date().toLocaleString();
sendNotification(
"Person Detected!",
`Motion detected by Watchtower Live at ${timestamp}`
);
res.json({ success: true });
});
// Send push notification to all subscribers
function sendNotification(title, body) {
if (!webPushConfigured) {
console.log('β Cannot send notification: Web Push not configured');
return false;
}
if (subscribers.size === 0) {
console.log('π No subscribers to send notification to');
return false;
}
const payload = JSON.stringify({ title, body });
console.log(`π€ Sending notification to ${subscribers.size} subscribers:`, { title, body });
let successCount = 0;
let errorCount = 0;
const promises = Array.from(subscribers).map(async (sub) => {
try {
const subscription = JSON.parse(sub);
console.log('π‘ Sending to:', subscription.endpoint.substring(0, 50) + '...');
const result = await webpush.sendNotification(subscription, payload);
console.log('β
Notification sent successfully:', result.statusCode);
successCount++;
return true;
} catch (err) {
console.error('β Error sending notification:', err.message);
errorCount++;
// Remove invalid subscriptions
if (err.statusCode === 410 || err.statusCode === 404) {
console.log('ποΈ Removing invalid subscription');
subscribers.delete(sub);
}
return false;
}
});
Promise.allSettled(promises).then(() => {
console.log(`π Notification results: ${successCount} sent, ${errorCount} failed`);
});
return true;
}
// Save snapshot helper with throttling
function saveSnapshot(base64Data, personDetected = false) {
const timestamp = Date.now();
const fileName = `snapshot-${timestamp}.jpg`;
const filePath = path.join(RECORDINGS_DIR, fileName);
try {
const data = base64Data.replace(/^data:image\/jpeg;base64,/, "");
fs.writeFileSync(filePath, Buffer.from(data, "base64"));
if (personDetected) {
console.log(`πΈ Person detected - saved: ${fileName}`);
}
return fileName;
} catch (err) {
console.error("Error saving snapshot:", err);
return null;
}
}
// Cleanup old files (keep only last 1000 images)
function cleanupOldFiles() {
fs.readdir(RECORDINGS_DIR, (err, files) => {
if (err) return;
const jpgFiles = files
.filter(f => f.endsWith('.jpg'))
.sort((a, b) => {
const timeA = parseInt(a.split('-')[1]?.split('.')[0] || '0');
const timeB = parseInt(b.split('-')[1]?.split('.')[0] || '0');
return timeB - timeA; // Newest first
});
if (jpgFiles.length > 1000) {
const filesToDelete = jpgFiles.slice(1000);
filesToDelete.forEach(file => {
fs.unlink(path.join(RECORDINGS_DIR, file), (err) => {
if (!err) console.log(`π§Ή Cleaned up old file: ${file}`);
});
});
}
});
}
// Run cleanup every hour
setInterval(cleanupOldFiles, 60 * 60 * 1000);
// WebSocket handling
wss.on("connection", (ws) => {
console.log("π Client connected");
ws.on("message", (message) => {
try {
const data = JSON.parse(message);
if (data.imageData) {
// Save the snapshot
const fileName = saveSnapshot(data.imageData, data.personDetected);
if (fileName) {
// Broadcast to all connected clients (for real-time updates)
wss.clients.forEach(client => {
if (client.readyState === 1) { // WebSocket.OPEN
client.send(JSON.stringify({
newSnapshot: fileName,
personDetected: data.personDetected
}));
}
});
}
}
} catch (err) {
console.error("Error processing WebSocket message:", err);
}
});
ws.on("close", () => {
console.log("π Client disconnected");
});
ws.on("error", (err) => {
console.error("WebSocket error:", err);
});
});
// Graceful shutdown
let isShuttingDown = false;
process.on('SIGINT', () => {
if (isShuttingDown) {
console.log('\nπ₯ Force closing...');
process.exit(1);
}
isShuttingDown = true;
console.log('\nπ Shutting down Watchtower Live server...');
// Close WebSocket server first
console.log('π‘ Closing WebSocket connections...');
wss.clients.forEach(client => {
client.terminate();
});
wss.close((err) => {
if (err) console.error('WebSocket server close error:', err);
else console.log('β
WebSocket server closed');
// Then close HTTP server
console.log('π Closing HTTP server...');
server.close((err) => {
if (err) {
console.error('β HTTP server close error:', err);
process.exit(1);
} else {
console.log('β
HTTP server closed');
console.log('β
Server stopped');
process.exit(0);
}
});
});
// Force exit after 5 seconds if graceful shutdown fails
setTimeout(() => {
console.log('β° Force closing after timeout...');
process.exit(1);
}, 5000);
});
process.on('SIGTERM', () => {
console.log('\nπ SIGTERM received, shutting down...');
process.kill(process.pid, 'SIGINT');
});