Sebebeb commited on
Commit
a663ee3
·
verified ·
1 Parent(s): 7eab36a

Delete public/admin/server.js

Browse files
Files changed (1) hide show
  1. public/admin/server.js +0 -378
public/admin/server.js DELETED
@@ -1,378 +0,0 @@
1
- const https = require('https');
2
- const fs = require('fs');
3
- const path = require('path');
4
- const { WebSocketServer, WebSocket } = require('ws');
5
- const { v4: uuidv4 } = require('uuid');
6
-
7
- // ─── TLS ──────────────────────────────────────────────────────────────────────
8
- const serverOptions = {
9
- cert: fs.readFileSync('cert.pem'),
10
- key: fs.readFileSync('key.pem'),
11
- };
12
-
13
- // ─── In-Memory State ──────────────────────────────────────────────────────────
14
- // sounds[id] = { id, name, data } (data = base64 string)
15
- // notifications[id] = { id, name, heading, body, hyperlink, displayed, soundId }
16
- // devices[uuid] = { uuid, name, notifications: [...], lastConnection, pendingChanges: [...], schedule: [...] }
17
- const sounds = {};
18
- const notifications = {};
19
- const devices = {};
20
-
21
- // ─── Live Connection Maps ─────────────────────────────────────────────────────
22
- // deviceClients: uuid -> WebSocket (Frontend 1 connections)
23
- // adminClients: Set<WebSocket> (Frontend 2 connections)
24
- const deviceClients = {};
25
- const adminClients = new Set();
26
-
27
- // ─── MIME Types ───────────────────────────────────────────────────────────────
28
- const MIME = {
29
- '.html': 'text/html',
30
- '.js': 'application/javascript',
31
- '.css': 'text/css',
32
- '.json': 'application/json',
33
- '.png': 'image/png',
34
- '.ico': 'image/x-icon',
35
- };
36
-
37
- // ─── HTTP File Server ─────────────────────────────────────────────────────────
38
- const httpServer = https.createServer(serverOptions, (req, res) => {
39
- let urlPath = req.url.split('?')[0];
40
- if (urlPath === '/' || urlPath === '') urlPath = '/index.html';
41
- if (urlPath === '/admin' || urlPath === '/admin/') urlPath = '/admin/index.html';
42
-
43
- const filePath = path.join(__dirname, 'public', urlPath);
44
- const ext = path.extname(filePath);
45
- const mime = MIME[ext] || 'application/octet-stream';
46
-
47
- fs.readFile(filePath, (err, data) => {
48
- if (err) {
49
- res.writeHead(404, { 'Content-Type': 'text/plain' });
50
- res.end('Not found');
51
- return;
52
- }
53
- res.writeHead(200, { 'Content-Type': mime });
54
- res.end(data);
55
- });
56
- });
57
-
58
- // ─── WebSocket Server ─────────────────────────────────────────────────────────
59
- const wss = new WebSocketServer({ server: httpServer });
60
-
61
- wss.on('connection', (ws, req) => {
62
- const urlPath = req.url || '/';
63
- const isAdmin = urlPath.startsWith('/admin-ws');
64
-
65
- if (isAdmin) {
66
- handleAdminConnection(ws);
67
- } else {
68
- handleDeviceConnection(ws);
69
- }
70
- });
71
-
72
- // ─── Helpers ──────────────────────────────────────────────────────────────────
73
- function send(ws, msg) {
74
- if (ws.readyState === WebSocket.OPEN) {
75
- ws.send(JSON.stringify(msg));
76
- }
77
- }
78
-
79
- function broadcastAdmin(msg) {
80
- for (const ws of adminClients) {
81
- send(ws, msg);
82
- }
83
- }
84
-
85
- function broadcastDevice(uuid, msg) {
86
- const ws = deviceClients[uuid];
87
- if (ws) send(ws, msg);
88
- }
89
-
90
- function broadcastAllDevices(msg) {
91
- for (const uuid of Object.keys(deviceClients)) {
92
- broadcastDevice(uuid, msg);
93
- }
94
- }
95
-
96
- function getFullState() {
97
- return {
98
- sounds: Object.values(sounds),
99
- notifications: Object.values(notifications),
100
- devices: Object.values(devices).map(devicePublic),
101
- };
102
- }
103
-
104
- function devicePublic(d) {
105
- return {
106
- uuid: d.uuid,
107
- name: d.name,
108
- notifications: d.notifications,
109
- lastConnection: d.lastConnection,
110
- schedule: d.schedule || [],
111
- pendingChanges: d.pendingChanges || [],
112
- online: !!deviceClients[d.uuid],
113
- };
114
- }
115
-
116
- // ─── Admin Connection Handler ─────────────────────────────────────────────────
117
- function handleAdminConnection(ws) {
118
- adminClients.add(ws);
119
- console.log(`[Admin] connected, total=${adminClients.size}`);
120
-
121
- // Send full state immediately
122
- send(ws, { type: 'full_state', ...getFullState() });
123
-
124
- ws.on('message', (raw) => {
125
- let msg;
126
- try { msg = JSON.parse(raw); } catch { return; }
127
- handleAdminMessage(ws, msg);
128
- });
129
-
130
- ws.on('close', () => {
131
- adminClients.delete(ws);
132
- console.log(`[Admin] disconnected, total=${adminClients.size}`);
133
- });
134
-
135
- ws.on('error', (e) => console.error('[Admin] WS error', e.message));
136
- }
137
-
138
- function handleAdminMessage(ws, msg) {
139
- switch (msg.type) {
140
-
141
- case 'create_sound': {
142
- // msg: { name, data }
143
- const id = uuidv4();
144
- const sound = { id, name: msg.name, data: msg.data };
145
- sounds[id] = sound;
146
- broadcastAdmin({ type: 'sound_added', sound });
147
- // Don't push sound data to all devices here — devices pull sounds on demand
148
- break;
149
- }
150
-
151
- case 'create_notification': {
152
- // msg: { name, heading, body, hyperlink, soundId }
153
- const id = uuidv4();
154
- const notif = {
155
- id,
156
- name: msg.name,
157
- heading: msg.heading,
158
- body: msg.body,
159
- hyperlink: msg.hyperlink || '',
160
- displayed: false,
161
- soundId: msg.soundId || null,
162
- };
163
- notifications[id] = notif;
164
- // Add to all devices
165
- for (const uuid of Object.keys(devices)) {
166
- if (!devices[uuid].notifications.find(n => n.id === id)) {
167
- devices[uuid].notifications.push({ ...notif });
168
- }
169
- }
170
- broadcastAdmin({ type: 'notification_added', notification: notif });
171
- broadcastAdmin({ type: 'devices_updated', devices: Object.values(devices).map(devicePublic) });
172
- // Push to all connected devices
173
- broadcastAllDevices({ type: 'notification_added', notification: notif });
174
- break;
175
- }
176
-
177
- case 'schedule_notification': {
178
- // msg: { uuid, notificationId, scheduledAt }
179
- const device = devices[msg.uuid];
180
- if (!device) return;
181
- device.schedule = device.schedule || [];
182
- const existing = device.schedule.find(s => s.notificationId === msg.notificationId);
183
- if (existing) {
184
- existing.scheduledAt = msg.scheduledAt;
185
- } else {
186
- device.schedule.push({ notificationId: msg.notificationId, scheduledAt: msg.scheduledAt });
187
- }
188
- const scheduleMsg = { type: 'schedule_update', schedule: device.schedule };
189
- if (deviceClients[msg.uuid]) {
190
- broadcastDevice(msg.uuid, scheduleMsg);
191
- } else {
192
- device.pendingChanges = device.pendingChanges || [];
193
- device.pendingChanges.push(scheduleMsg);
194
- }
195
- broadcastAdmin({ type: 'devices_updated', devices: Object.values(devices).map(devicePublic) });
196
- break;
197
- }
198
-
199
- case 'play_now': {
200
- // msg: { uuid, notificationId }
201
- const playMsg = { type: 'play_now', notificationId: msg.notificationId };
202
- if (deviceClients[msg.uuid]) {
203
- broadcastDevice(msg.uuid, playMsg);
204
- } else {
205
- const device = devices[msg.uuid];
206
- if (device) {
207
- device.pendingChanges = device.pendingChanges || [];
208
- device.pendingChanges.push(playMsg);
209
- }
210
- }
211
- break;
212
- }
213
-
214
- case 'update_device_name': {
215
- // msg: { uuid, name }
216
- const device = devices[msg.uuid];
217
- if (!device) return;
218
- device.name = msg.name;
219
- const nameMsg = { type: 'name_update', name: msg.name };
220
- if (deviceClients[msg.uuid]) {
221
- broadcastDevice(msg.uuid, nameMsg);
222
- } else {
223
- device.pendingChanges = device.pendingChanges || [];
224
- device.pendingChanges.push(nameMsg);
225
- }
226
- broadcastAdmin({ type: 'devices_updated', devices: Object.values(devices).map(devicePublic) });
227
- break;
228
- }
229
-
230
- case 'remove_schedule': {
231
- // msg: { uuid, notificationId }
232
- const device = devices[msg.uuid];
233
- if (!device) return;
234
- device.schedule = (device.schedule || []).filter(s => s.notificationId !== msg.notificationId);
235
- const rmMsg = { type: 'schedule_update', schedule: device.schedule };
236
- if (deviceClients[msg.uuid]) {
237
- broadcastDevice(msg.uuid, rmMsg);
238
- } else {
239
- device.pendingChanges = device.pendingChanges || [];
240
- device.pendingChanges.push(rmMsg);
241
- }
242
- broadcastAdmin({ type: 'devices_updated', devices: Object.values(devices).map(devicePublic) });
243
- break;
244
- }
245
-
246
- case 'request_sound': {
247
- // admin wants a specific sound by id
248
- const sound = sounds[msg.id];
249
- if (sound) send(ws, { type: 'sound_data', sound });
250
- break;
251
- }
252
-
253
- default:
254
- console.warn('[Admin] unknown message type:', msg.type);
255
- }
256
- }
257
-
258
- // ─── Device Connection Handler ────────────────────────────────────────────────
259
- function handleDeviceConnection(ws) {
260
- let deviceUUID = null;
261
- console.log('[Device] new connection (uuid pending)');
262
-
263
- ws.on('message', (raw) => {
264
- let msg;
265
- try { msg = JSON.parse(raw); } catch { return; }
266
-
267
- if (msg.type === 'hello') {
268
- // Device introduces itself with optional uuid
269
- if (msg.uuid && devices[msg.uuid]) {
270
- deviceUUID = msg.uuid;
271
- } else {
272
- // New device
273
- deviceUUID = msg.uuid || uuidv4();
274
- devices[deviceUUID] = {
275
- uuid: deviceUUID,
276
- name: `Device ${Object.keys(devices).length + 1}`,
277
- notifications: Object.values(notifications).map(n => ({ ...n })),
278
- lastConnection: null,
279
- schedule: [],
280
- pendingChanges: [],
281
- };
282
- }
283
-
284
- deviceClients[deviceUUID] = ws;
285
- const device = devices[deviceUUID];
286
- device.lastConnection = null; // online
287
-
288
- // Deliver any pending changes
289
- if (device.pendingChanges && device.pendingChanges.length > 0) {
290
- for (const change of device.pendingChanges) {
291
- send(ws, change);
292
- }
293
- device.pendingChanges = [];
294
- }
295
-
296
- // Send device its full state
297
- send(ws, {
298
- type: 'device_init',
299
- uuid: deviceUUID,
300
- notifications: device.notifications,
301
- schedule: device.schedule,
302
- name: device.name,
303
- });
304
-
305
- // Tell admin about new/reconnected device
306
- broadcastAdmin({ type: 'devices_updated', devices: Object.values(devices).map(devicePublic) });
307
- console.log(`[Device] ${deviceUUID} connected (${device.name})`);
308
- return;
309
- }
310
-
311
- if (!deviceUUID) return; // not initialized
312
-
313
- handleDeviceMessage(ws, deviceUUID, msg);
314
- });
315
-
316
- ws.on('close', () => {
317
- if (deviceUUID && devices[deviceUUID]) {
318
- devices[deviceUUID].lastConnection = Date.now();
319
- delete deviceClients[deviceUUID];
320
- broadcastAdmin({ type: 'devices_updated', devices: Object.values(devices).map(devicePublic) });
321
- console.log(`[Device] ${deviceUUID} disconnected`);
322
- }
323
- });
324
-
325
- ws.on('error', (e) => console.error('[Device] WS error', e.message));
326
- }
327
-
328
- function handleDeviceMessage(ws, uuid, msg) {
329
- const device = devices[uuid];
330
- if (!device) return;
331
-
332
- switch (msg.type) {
333
-
334
- case 'mark_displayed': {
335
- // msg: { notificationId }
336
- const notif = device.notifications.find(n => n.id === msg.notificationId);
337
- if (notif) notif.displayed = true;
338
- // Also mark in master list
339
- if (notifications[msg.notificationId]) {
340
- notifications[msg.notificationId].displayed = true;
341
- }
342
- broadcastAdmin({ type: 'devices_updated', devices: Object.values(devices).map(devicePublic) });
343
- break;
344
- }
345
-
346
- case 'request_sound': {
347
- // Device needs sound data for a notification
348
- const sound = sounds[msg.soundId];
349
- if (sound) {
350
- send(ws, { type: 'sound_data', sound });
351
- }
352
- break;
353
- }
354
-
355
- case 'sync_schedule': {
356
- // Device reports its current schedule (for reconciliation)
357
- device.schedule = msg.schedule || [];
358
- broadcastAdmin({ type: 'devices_updated', devices: Object.values(devices).map(devicePublic) });
359
- break;
360
- }
361
-
362
- case 'cached_sounds': {
363
- // Device reports which sound IDs it has cached
364
- device.cachedSounds = msg.soundIds || [];
365
- broadcastAdmin({ type: 'devices_updated', devices: Object.values(devices).map(devicePublic) });
366
- break;
367
- }
368
-
369
- default:
370
- console.warn('[Device] unknown message type:', msg.type);
371
- }
372
- }
373
-
374
- // ─── Start ────────────────────────────────────────────────────────────────────
375
- const PORT = process.env.PORT || 7860;
376
- httpServer.listen(PORT, () => {
377
- console.log(`Server running on https://0.0.0.0:${PORT}`);
378
- });