-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·480 lines (429 loc) · 16.7 KB
/
Copy pathserver.js
File metadata and controls
executable file
·480 lines (429 loc) · 16.7 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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import 'dotenv/config';
import dotenv from 'dotenv';
import express from 'express';
import path from 'path';
import http from 'http';
import https from 'https';
import { fileURLToPath } from 'url';
import { getDb, getSetting } from './db.js';
import * as logger from './logger.js';
if (process.env.NODE_ENV === 'development') {
dotenv.config({ path: '.env.dev', override: true });
}
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// ── Init debug mode from DB ──
function initDebugMode() {
try {
const db = getDb();
const val = getSetting('debug', process.env.DEBUG || 'false');
logger.setDebugMode(val === 'true');
logger.info(`Debug mode: ${logger.isDebug() ? 'ON' : 'OFF'}`);
} catch {
logger.setDebugMode(false);
}
}
initDebugMode();
// ── Request logger middleware ──
app.use((req, res, next) => {
if (logger.isDebug()) {
const start = Date.now();
res.on('finish', () => {
logger.debug(`${req.method} ${req.originalUrl} → ${res.statusCode} (${Date.now() - start}ms)`);
});
}
next();
});
// ── Health cache (TTL and timeout from DB settings, fallback env / defaults) ──
const healthCache = { data: null, ts: 0 };
let healthTimer = null;
function getHealthTTL() {
const v = getSetting('healthcheck.delay', process.env.HEALCHECK_REFRESH_DELAY || process.env.HEALTHCHECK_REFRESH_DELAY || '300000');
return parseInt(v, 10);
}
function getHealthTimeout() {
const v = getSetting('healthcheck.timeout', process.env.HEALTHCHECK_TIMEOUT || '10000');
return parseInt(v, 10);
}
function resetHealthCache() {
healthCache.data = null;
healthCache.ts = 0;
}
async function checkOne(card) {
const start = Date.now();
try {
const url = new URL(card.url);
const lib = url.protocol === 'https:' ? https : http;
const timeout = getHealthTimeout();
const result = await new Promise((resolve, reject) => {
const opts = {
hostname: url.hostname,
port: url.port || (url.protocol === 'https:' ? 443 : 80),
path: url.pathname + url.search,
method: 'GET',
timeout,
};
if (url.protocol === 'https:') opts.rejectUnauthorized = false;
const req = lib.request(opts, (res) => {
resolve({ online: true, status: res.statusCode });
res.resume();
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('Timeout')); });
req.end();
});
return { id: card.id, online: result.online, ms: Date.now() - start, status: result.status };
} catch {
return { id: card.id, online: false, ms: Date.now() - start, status: null };
}
}
async function checkHealth() {
const db = getDb();
const cards = db.prepare('SELECT id, url FROM cards').all();
logger.info(`Health check: ${cards.length} carte(s) à vérifier`);
const results = {};
const checks = await Promise.all(cards.map(checkOne));
for (const r of checks) results[r.id] = { online: r.online, ms: r.ms, status: r.status };
const online = Object.values(results).filter(r => r.online).length;
logger.info(`Health check terminé : ${online}/${cards.length} en ligne`);
return results;
}
function startHealthLoop() {
if (healthTimer) clearInterval(healthTimer);
const TTL = getHealthTTL();
logger.info(`Boucle santé: ${TTL}ms d'intervalle`);
const loop = async () => {
try {
healthCache.data = await checkHealth();
healthCache.ts = Date.now();
} catch (err) {
logger.error('Boucle santé échouée:', err.message);
}
};
loop();
healthTimer = setInterval(loop, TTL);
}
app.get('/api/health', (_req, res) => {
res.json(healthCache.data || {});
});
app.post('/api/health/refresh', async (_req, res) => {
logger.info('Refresh santé forcé');
try {
healthCache.data = await checkHealth();
healthCache.ts = Date.now();
} catch (err) {
logger.error('Refresh santé forcé échoué:', err.message);
}
res.json(healthCache.data);
});
// ── Settings ──
const KNOWN_SETTINGS = [
{ key: 'high.contrast', label: '🔲 Contraste élevé (accessibilité)', type: 'boolean', default: 'false', description: 'Renforcer les contrastes pour les malvoyants (WCAG AAA)' },
{ key: 'debug', label: 'Mode debug', type: 'boolean', default: 'false', description: 'Activer les logs verbeux pour le diagnostic' },
{ key: 'colorblind.mode', label: 'Mode daltonien', type: 'select', default: 'normal',
options: [
{ value: 'normal', label: 'Normal' },
{ value: 'protanopia', label: 'Protanopie (rouge)' },
{ value: 'deuteranopia', label: 'Deutéranopie (vert)' },
{ value: 'tritanopia', label: 'Tritanopie (bleu)' },
{ value: 'achromatopsia', label: 'Achromatopsie (monochrome)' },
],
description: 'Adapter les couleurs de l\'interface aux différents types de daltonisme' },
{ key: 'healthcheck.delay', label: 'Rafraîchissement santé (ms)', type: 'number', default: '300000', description: 'Intervalle entre chaque vérification de santé des URLs (5 min = 300000)' },
{ key: 'healthcheck.timeout', label: 'Timeout requête santé (ms)', type: 'number', default: '10000', description: 'Délai max d\'attente par requête (10 sec = 10000)' },
];
app.get('/api/settings', (_req, res) => {
const db = getDb();
const stored = db.prepare('SELECT key, value FROM settings').all();
const map = {};
for (const s of stored) map[s.key] = s.value;
const result = KNOWN_SETTINGS.map(s => ({
...s,
value: map[s.key] !== undefined ? map[s.key] : s.default,
}));
res.json(result);
});
app.put('/api/settings', (req, res) => {
const db = getDb();
const { key, value } = req.body;
if (!key) return res.status(400).json({ error: 'key is required' });
try {
db.prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?').run(key, value, value);
logger.info(`Setting mis à jour : ${key} = ${value}`);
if (key === 'debug') logger.setDebugMode(value === 'true');
if (key.startsWith('healthcheck.')) startHealthLoop();
res.json({ ok: true });
} catch (err) {
logger.error(`Erreur mise à jour setting ${key}:`, err.message);
res.status(400).json({ error: err.message });
}
});
// ── Generic CRUD helpers ──
function list(table, joins = '') {
return (req, res) => {
const db = getDb();
let sql = `SELECT * FROM ${table} ${joins}`;
const params = [];
const where = [];
if (req.query.search && ['cards', 'machines', 'outils', 'categories'].includes(table)) {
where.push(`${table}.nom LIKE ?`);
params.push(`%${req.query.search}%`);
}
if (req.query.categorie_id && table === 'cards') {
where.push('cards.categorie_id = ?');
params.push(req.query.categorie_id);
}
if (req.query.machine_id && table === 'cards') {
where.push('cards.machine_id = ?');
params.push(req.query.machine_id);
}
if (where.length) sql += ' WHERE ' + where.join(' AND ');
if (req.query.sort) sql += ` ORDER BY ${req.query.sort}`;
else sql += ' ORDER BY nom ASC';
res.json(db.prepare(sql).all(...params));
};
}
function getById(table) {
return (req, res) => {
const db = getDb();
const row = db.prepare(`SELECT * FROM ${table} WHERE id = ?`).get(req.params.id);
if (!row) return res.status(404).json({ error: 'Not found' });
res.json(row);
};
}
function create(table) {
return (req, res) => {
const db = getDb();
const cols = Object.keys(req.body);
const vals = cols.map((c) => req.body[c]);
const placeholders = cols.map(() => '?').join(',');
try {
const stmt = db.prepare(`INSERT INTO ${table} (${cols.join(',')}) VALUES (${placeholders})`);
const result = stmt.run(...vals);
const row = db.prepare(`SELECT * FROM ${table} WHERE id = ?`).get(result.lastInsertRowid);
logger.debug(`${table} :: create id=${result.lastInsertRowid}`);
res.status(201).json(row);
} catch (err) {
logger.error(`${table} :: create error:`, err.message);
res.status(400).json({ error: err.message });
}
};
}
function update(table) {
return (req, res) => {
const db = getDb();
const cols = Object.keys(req.body);
const vals = cols.map((c) => req.body[c]);
const set = cols.map((c) => `${c} = ?`).join(',');
try {
db.prepare(`UPDATE ${table} SET ${set} WHERE id = ?`).run(...vals, req.params.id);
const row = db.prepare(`SELECT * FROM ${table} WHERE id = ?`).get(req.params.id);
if (!row) return res.status(404).json({ error: 'Not found' });
logger.debug(`${table} :: update id=${req.params.id}`);
res.json(row);
} catch (err) {
logger.error(`${table} :: update id=${req.params.id} error:`, err.message);
res.status(400).json({ error: err.message });
}
};
}
function remove(table) {
return (req, res) => {
const db = getDb();
try {
db.prepare(`DELETE FROM ${table} WHERE id = ?`).run(req.params.id);
logger.debug(`${table} :: delete id=${req.params.id}`);
res.json({ ok: true });
} catch (err) {
logger.error(`${table} :: delete id=${req.params.id} error:`, err.message);
res.status(400).json({ error: err.message });
}
};
}
// ── Icons (stored in DB, served via endpoint) ──
app.get('/api/icons', (req, res) => {
const db = getDb();
res.json(db.prepare('SELECT id, nom, filename, entity_type FROM icons ORDER BY nom ASC').all());
});
app.get('/api/icons/:id', (req, res) => {
const db = getDb();
const row = db.prepare('SELECT id, nom, filename, entity_type, data FROM icons WHERE id = ?').get(req.params.id);
if (!row) return res.status(404).json({ error: 'Not found' });
res.json(row);
});
app.get('/api/icons/:id/file', (req, res) => {
const db = getDb();
const icon = db.prepare('SELECT filename, data FROM icons WHERE id = ?').get(req.params.id);
if (!icon) return res.status(404).json({ error: 'Not found' });
const ext = path.extname(icon.filename).toLowerCase();
const mime = ext === '.png' ? 'image/png' : ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg' : 'image/svg+xml';
res.set('Content-Type', mime);
res.set('Cache-Control', 'public, max-age=86400');
res.send(icon.data);
});
app.post('/api/icons', (req, res) => {
const db = getDb();
const { nom, filename, entity_type, data } = req.body;
if (!nom) return res.status(400).json({ error: 'nom is required' });
try {
const stmt = db.prepare('INSERT INTO icons (nom, filename, entity_type, data) VALUES (?, ?, ?, ?)');
const result = stmt.run(nom, filename || '', entity_type || '', data || '');
const row = db.prepare('SELECT id, nom, filename, entity_type FROM icons WHERE id = ?').get(result.lastInsertRowid);
logger.info(`Icône créée : ${nom} (id=${result.lastInsertRowid})`);
res.status(201).json(row);
} catch (err) {
logger.error(`Erreur création icône ${nom}:`, err.message);
res.status(400).json({ error: err.message });
}
});
app.put('/api/icons/:id', (req, res) => {
const db = getDb();
const { nom, filename, entity_type, data } = req.body;
try {
const sets = []; const vals = [];
if (nom !== undefined) { sets.push('nom = ?'); vals.push(nom); }
if (filename !== undefined) { sets.push('filename = ?'); vals.push(filename); }
if (entity_type !== undefined) { sets.push('entity_type = ?'); vals.push(entity_type); }
if (data !== undefined) { sets.push('data = ?'); vals.push(data); }
if (!sets.length) return res.status(400).json({ error: 'No fields to update' });
db.prepare(`UPDATE icons SET ${sets.join(', ')} WHERE id = ?`).run(...vals, req.params.id);
const row = db.prepare('SELECT id, nom, filename, entity_type FROM icons WHERE id = ?').get(req.params.id);
if (!row) return res.status(404).json({ error: 'Not found' });
logger.debug(`Icône modifiée : id=${req.params.id}`);
res.json(row);
} catch (err) {
logger.error(`Erreur modification icône id=${req.params.id}:`, err.message);
res.status(400).json({ error: err.message });
}
});
app.delete('/api/icons/:id', (req, res) => {
const db = getDb();
try {
db.prepare('DELETE FROM icons WHERE id = ?').run(req.params.id);
logger.info(`Icône supprimée : id=${req.params.id}`);
res.json({ ok: true });
} catch (err) {
logger.error(`Erreur suppression icône id=${req.params.id}:`, err.message);
res.status(400).json({ error: err.message });
}
});
// ── Cards (with joins) ──
app.get('/api/cards', (req, res) => {
const db = getDb();
let sql = `
SELECT cards.*,
categories.nom AS categorie_nom, categories.couleur AS categorie_couleur, cat_icon.id AS categorie_icon_id,
machines.nom AS machine_nom, machines.ip AS machine_ip, mach_icon.id AS machine_icon_id,
outils.nom AS outil_nom, outils.port AS outil_port, outils.main_page AS outil_main_page, outil_icon.id AS outil_icon_id
FROM cards
LEFT JOIN categories ON cards.categorie_id = categories.id
LEFT JOIN icons cat_icon ON categories.icon_id = cat_icon.id
LEFT JOIN machines ON cards.machine_id = machines.id
LEFT JOIN icons mach_icon ON machines.icon_id = mach_icon.id
LEFT JOIN outils ON cards.outil_id = outils.id
LEFT JOIN icons outil_icon ON outils.icon_id = outil_icon.id
`;
const params = [];
const where = [];
if (req.query.search) {
where.push('cards.nom LIKE ?');
params.push(`%${req.query.search}%`);
}
if (req.query.categorie_id) {
where.push('cards.categorie_id = ?');
params.push(req.query.categorie_id);
}
if (req.query.machine_id) {
where.push('cards.machine_id = ?');
params.push(req.query.machine_id);
}
if (where.length) sql += ' WHERE ' + where.join(' AND ');
sql += ' ORDER BY cards.nom ASC';
res.json(db.prepare(sql).all(...params));
});
app.get('/api/cards/:id', getById('cards'));
app.post('/api/cards', create('cards'));
app.put('/api/cards/:id', update('cards'));
app.delete('/api/cards/:id', remove('cards'));
// ── Categories ──
app.get('/api/categories', (req, res) => {
const db = getDb();
const sql = `
SELECT categories.*, icons.id AS icon_id
FROM categories
LEFT JOIN icons ON categories.icon_id = icons.id
ORDER BY categories.nom ASC
`;
res.json(db.prepare(sql).all());
});
app.get('/api/categories/:id', getById('categories'));
app.post('/api/categories', create('categories'));
app.put('/api/categories/:id', update('categories'));
app.delete('/api/categories/:id', remove('categories'));
// ── Machines ──
app.get('/api/machines', (req, res) => {
const db = getDb();
const sql = `
SELECT machines.*, os.nom AS os_nom, fabriquants.nom AS fabriquant_nom, fabriquants.modele AS fabriquant_modele,
icons.id AS icon_id
FROM machines
LEFT JOIN os ON machines.os_id = os.id
LEFT JOIN fabriquants ON machines.fabriquant_id = fabriquants.id
LEFT JOIN icons ON machines.icon_id = icons.id
ORDER BY machines.nom ASC
`;
res.json(db.prepare(sql).all());
});
app.get('/api/machines/:id', getById('machines'));
app.post('/api/machines', create('machines'));
app.put('/api/machines/:id', update('machines'));
app.delete('/api/machines/:id', remove('machines'));
// ── Outils ──
app.get('/api/outils', (req, res) => {
const db = getDb();
const sql = `
SELECT outils.*, categories.nom AS categorie_nom, categories.couleur AS categorie_couleur,
icons.id AS icon_id
FROM outils
LEFT JOIN categories ON outils.categorie_id = categories.id
LEFT JOIN icons ON outils.icon_id = icons.id
ORDER BY outils.nom ASC
`;
res.json(db.prepare(sql).all());
});
app.get('/api/outils/:id', getById('outils'));
app.post('/api/outils', create('outils'));
app.put('/api/outils/:id', update('outils'));
app.delete('/api/outils/:id', remove('outils'));
// ── OS ──
app.get('/api/os', (req, res) => {
const db = getDb();
const sql = `
SELECT os.*, icons.id AS icon_id
FROM os
LEFT JOIN icons ON os.icon_id = icons.id
ORDER BY os.nom ASC
`;
res.json(db.prepare(sql).all());
});
app.get('/api/os/:id', getById('os'));
app.post('/api/os', create('os'));
app.put('/api/os/:id', update('os'));
app.delete('/api/os/:id', remove('os'));
// ── Fabriquants ──
app.get('/api/fabriquants', list('fabriquants'));
app.get('/api/fabriquants/:id', getById('fabriquants'));
app.post('/api/fabriquants', create('fabriquants'));
app.put('/api/fabriquants/:id', update('fabriquants'));
app.delete('/api/fabriquants/:id', remove('fabriquants'));
// ── Serve SPA ──
app.get('*', (_req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(PORT, () => {
logger.info(`NetworkHub started on http://0.0.0.0:${PORT}`);
startHealthLoop();
});