-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
595 lines (562 loc) · 25.1 KB
/
Copy pathserver.js
File metadata and controls
595 lines (562 loc) · 25.1 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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
const express = require('express')
const path = require('path')
const fs = require('fs')
const cors = require('cors')
const http = require('http')
const WebSocket = require('ws')
const app = express()
const server = http.createServer(app)
const wss = new WebSocket.Server({ server })
const PORT = 3001
app.use(cors())
// Kleines Standard-Limit; nur Routen mit großen Nutzdaten (Upload, Templates, Gadgets) 50mb
const smallJson = express.json({ limit: '1mb' })
const bigJson = express.json({ limit: '50mb' })
app.use((req, res, next) => {
const big = req.path.startsWith('/api/upload') || req.path.startsWith('/api/templates') || req.path.startsWith('/api/gadgets')
return (big ? bigJson : smallJson)(req, res, next)
})
app.use(express.static(path.join(__dirname, 'client', 'dist')))
app.use('/fonts', express.static(path.join(__dirname, 'public', 'fonts')))
app.use('/uploads', express.static(path.join(__dirname, 'public', 'uploads')))
app.use('/sounds', express.static(path.join(__dirname, 'public', 'sounds')))
const DATA_DIR = path.join(__dirname, 'data')
const TEMPLATES_DIR = path.join(DATA_DIR, 'templates')
const GADGETS_DIR = path.join(DATA_DIR, 'gadgets')
const SETTINGS_FILE = path.join(DATA_DIR, 'settings.json')
const APIS_FILE = path.join(DATA_DIR, 'apis.json')
;[DATA_DIR, TEMPLATES_DIR, GADGETS_DIR,
path.join(__dirname, 'public', 'fonts'),
path.join(__dirname, 'public', 'uploads'),
path.join(__dirname, 'public', 'sounds'),
].forEach(d => fs.mkdirSync(d, { recursive: true }))
function safeId(id) {
if (typeof id !== 'string') return null
const cleaned = id.replace(/[^a-zA-Z0-9_-]/g, '')
return cleaned.length > 0 ? cleaned : null
}
// Bilder, die ein Template nutzt, in seinen assets-Ordner kopieren und neu
// verlinken — so bleibt das Bild dauerhaft beim Template (auch beim Kopieren).
function bundleTemplateAssets(data, templateId) {
const assetsDir = path.join(TEMPLATES_DIR, templateId, 'assets')
const copyInto = (srcAbs, file) => {
try {
if (!fs.existsSync(srcAbs)) return false
fs.mkdirSync(assetsDir, { recursive: true })
const destAbs = path.join(assetsDir, file)
if (path.resolve(srcAbs) !== path.resolve(destAbs)) fs.copyFileSync(srcAbs, destAbs)
return true
} catch { return false }
}
const rewrite = (url) => {
if (typeof url !== 'string') return url
// /uploads/<file> → ins Template kopieren
let m = url.match(/^\/uploads\/([^/?#]+)$/)
if (m) {
const file = path.basename(m[1])
if (copyInto(path.join(__dirname, 'public', 'uploads', file), file))
return `/api/templates/${templateId}/assets/${file}`
return url
}
// /api/templates/<otherId>/assets/<file> → aus anderem Template übernehmen
m = url.match(/^\/api\/templates\/([^/]+)\/assets\/([^/?#]+)$/)
if (m) {
const otherId = safeId(m[1]); const file = path.basename(m[2])
if (!otherId) return url
if (otherId === templateId) return url // schon hier
if (copyInto(path.join(TEMPLATES_DIR, otherId, 'assets', file), file))
return `/api/templates/${templateId}/assets/${file}`
return url
}
return url
}
const walk = (node) => {
if (Array.isArray(node)) return node.map(walk)
if (node && typeof node === 'object') {
const out = {}
for (const [k, v] of Object.entries(node)) out[k] = walk(v)
return out
}
return rewrite(node)
}
return walk(data)
}
function readJson(filePath, fallback = null) {
try { return JSON.parse(fs.readFileSync(filePath, 'utf8')) } catch { return fallback }
}
function writeJson(filePath, data) {
// Atomar: erst tmp schreiben, dann umbenennen — kein korruptes JSON bei Crash/Stromausfall
const tmp = filePath + '.tmp'
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8')
fs.renameSync(tmp, filePath)
}
function broadcast(data) {
const msg = JSON.stringify(data)
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) client.send(msg)
})
}
function broadcastClients() {
let clocks = 0
wss.clients.forEach(c => { if (c.readyState === WebSocket.OPEN && c.role === 'clock') clocks++ })
broadcast({ type: 'clients', clocks })
}
wss.on('connection', ws => {
ws.on('message', msg => {
try {
const data = JSON.parse(msg)
if (data.type === 'ping') ws.send(JSON.stringify({ type: 'pong' }))
if (data.type === 'hello') {
ws.role = data.role // 'clock' | 'editor'
broadcastClients()
}
} catch {}
})
ws.on('close', () => broadcastClients())
ws.send(JSON.stringify({ type: 'connected' }))
})
// --- Settings ---
app.get('/api/settings', (req, res) => {
const defaults = { activeTemplate: null, timezone: 'Europe/Berlin', secondHandMode: 'smooth', playlist: null }
res.json(readJson(SETTINGS_FILE, defaults))
})
app.post('/api/settings', (req, res) => {
const current = readJson(SETTINGS_FILE, {})
// Nur bekannte Felder übernehmen — kein beliebiges Key-Fluten der settings.json
const allowed = ['activeTemplate', 'timezone', 'secondHandMode', 'playlist']
const patch = {}
for (const k of allowed) if (k in (req.body || {})) patch[k] = req.body[k]
const updated = { ...current, ...patch, updatedAt: new Date().toISOString() }
writeJson(SETTINGS_FILE, updated)
broadcast({ type: 'settings-update', data: updated })
res.json(updated)
})
// --- Templates ---
app.get('/api/templates', (req, res) => {
if (!fs.existsSync(TEMPLATES_DIR)) return res.json([])
const dirs = fs.readdirSync(TEMPLATES_DIR)
const templates = dirs
.map(id => readJson(path.join(TEMPLATES_DIR, id, 'config.json')))
.filter(Boolean)
.sort((a, b) => (new Date(b.updatedAt).getTime() || 0) - (new Date(a.updatedAt).getTime() || 0))
res.json(templates)
})
app.get('/api/templates/:id', (req, res) => {
const id = safeId(req.params.id)
if (!id) return res.status(400).json({ error: 'Invalid id' })
const cfg = readJson(path.join(TEMPLATES_DIR, id, 'config.json'))
if (!cfg) return res.status(404).json({ error: 'Not found' })
res.json(cfg)
})
app.post('/api/templates', (req, res) => {
const id = safeId(req.body.id)
if (!id) return res.status(400).json({ error: 'Invalid id' })
const dir = path.join(TEMPLATES_DIR, id)
fs.mkdirSync(dir, { recursive: true })
let data = { ...req.body, updatedAt: new Date().toISOString() }
data = bundleTemplateAssets(data, id)
writeJson(path.join(dir, 'config.json'), data)
broadcast({ type: 'template-update', data })
res.json(data)
})
app.put('/api/templates/:id', (req, res) => {
const id = safeId(req.params.id)
if (!id) return res.status(400).json({ error: 'Invalid id' })
const dir = path.join(TEMPLATES_DIR, id)
fs.mkdirSync(dir, { recursive: true })
let data = { ...req.body, id, updatedAt: new Date().toISOString() }
data = bundleTemplateAssets(data, id)
writeJson(path.join(dir, 'config.json'), data)
broadcast({ type: 'template-update', data })
res.json(data)
})
// Bundled template assets (Bilder, die mit dem Template gespeichert wurden)
app.get('/api/templates/:id/assets/:file', (req, res) => {
const id = safeId(req.params.id)
if (!id) return res.status(400).end()
const file = path.basename(req.params.file)
const abs = path.join(TEMPLATES_DIR, id, 'assets', file)
if (!fs.existsSync(abs)) return res.status(404).end()
res.sendFile(abs)
})
app.delete('/api/templates/:id', (req, res) => {
const id = safeId(req.params.id)
if (!id) return res.status(400).json({ error: 'Invalid id' })
const dir = path.join(TEMPLATES_DIR, id)
if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true })
broadcast({ type: 'template-delete', id })
res.json({ ok: true })
})
// --- Gadgets ---
app.get('/api/gadgets', (req, res) => {
if (!fs.existsSync(GADGETS_DIR)) return res.json([])
const dirs = fs.readdirSync(GADGETS_DIR)
const gadgets = dirs
.map(id => readJson(path.join(GADGETS_DIR, id, 'config.json')))
.filter(Boolean)
res.json(gadgets)
})
app.get('/api/gadgets/:id', (req, res) => {
const id = safeId(req.params.id)
if (!id) return res.status(400).json({ error: 'Invalid id' })
const cfg = readJson(path.join(GADGETS_DIR, id, 'config.json'))
if (!cfg) return res.status(404).json({ error: 'Not found' })
res.json(cfg)
})
app.post('/api/gadgets', (req, res) => {
const id = safeId(req.body.id)
if (!id) return res.status(400).json({ error: 'Invalid id' })
const dir = path.join(GADGETS_DIR, id)
fs.mkdirSync(dir, { recursive: true })
const data = { ...req.body, updatedAt: new Date().toISOString() }
writeJson(path.join(dir, 'config.json'), data)
res.json(data)
})
app.put('/api/gadgets/:id', (req, res) => {
const id = safeId(req.params.id)
if (!id) return res.status(400).json({ error: 'Invalid id' })
const dir = path.join(GADGETS_DIR, id)
fs.mkdirSync(dir, { recursive: true })
const data = { ...req.body, id, updatedAt: new Date().toISOString() }
writeJson(path.join(dir, 'config.json'), data)
res.json(data)
})
app.delete('/api/gadgets/:id', (req, res) => {
const id = safeId(req.params.id)
if (!id) return res.status(400).json({ error: 'Invalid id' })
const dir = path.join(GADGETS_DIR, id)
if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true })
res.json({ ok: true })
})
// --- Gadget-Ordner ---
// Der Ordner eines Gadgets steht als Feld `folder` in seiner config.json (wird vom Body
// durchgereicht). Diese Liste existiert nur, damit auch LEERE Ordner einen Reload überleben.
const GADGET_FOLDERS_FILE = path.join(DATA_DIR, 'gadget-folders.json')
const FOLDER_SEG = /^[\w äöüÄÖÜß-]{1,40}$/
function cleanFolderPath(p) {
if (typeof p !== 'string') return null
const segs = p.split('/').map(s => s.trim()).filter(Boolean)
if (segs.length === 0 || segs.length > 3) return null
if (!segs.every(s => FOLDER_SEG.test(s))) return null
return segs.join('/')
}
app.get('/api/gadget-folders', (req, res) => res.json(readJson(GADGET_FOLDERS_FILE, [])))
app.put('/api/gadget-folders', (req, res) => {
if (!Array.isArray(req.body)) return res.status(400).json({ error: 'array required' })
const list = [...new Set(req.body.map(cleanFolderPath).filter(Boolean))].slice(0, 200)
writeJson(GADGET_FOLDERS_FILE, list)
res.json(list)
})
// --- Zahnrad-Vorlagen (Presets) ---
const GEAR_PRESETS_FILE = path.join(DATA_DIR, 'gear-presets.json')
app.get('/api/gear-presets', (req, res) => res.json(readJson(GEAR_PRESETS_FILE, [])))
app.post('/api/gear-presets', (req, res) => {
const { id, name, data } = req.body || {}
if (!name || !data) return res.status(400).json({ error: 'name + data required' })
const list = readJson(GEAR_PRESETS_FILE, [])
const pid = id || ('gp' + Date.now().toString(36))
const idx = list.findIndex(p => p.id === pid)
const entry = { id: pid, name, data, updatedAt: new Date().toISOString() }
if (idx >= 0) list[idx] = entry; else list.push(entry)
writeJson(GEAR_PRESETS_FILE, list)
res.json(entry)
})
app.delete('/api/gear-presets/:id', (req, res) => {
const list = readJson(GEAR_PRESETS_FILE, []).filter(p => p.id !== req.params.id)
writeJson(GEAR_PRESETS_FILE, list)
res.json({ ok: true })
})
// --- Zeiger-Vorlagen (Presets) — nur das Aussehen eines Zeigers, ohne Takt/Name/ID ---
const HAND_PRESETS_FILE = path.join(DATA_DIR, 'hand-presets.json')
app.get('/api/hand-presets', (req, res) => res.json(readJson(HAND_PRESETS_FILE, [])))
app.post('/api/hand-presets', (req, res) => {
const { id, name, data } = req.body || {}
if (!name || !data) return res.status(400).json({ error: 'name + data required' })
const list = readJson(HAND_PRESETS_FILE, [])
const pid = id || ('hp' + Date.now().toString(36))
const idx = list.findIndex(p => p.id === pid)
const entry = { id: pid, name, data, updatedAt: new Date().toISOString() }
if (idx >= 0) list[idx] = entry; else list.push(entry)
writeJson(HAND_PRESETS_FILE, list)
res.json(entry)
})
app.delete('/api/hand-presets/:id', (req, res) => {
const list = readJson(HAND_PRESETS_FILE, []).filter(p => p.id !== req.params.id)
writeJson(HAND_PRESETS_FILE, list)
res.json({ ok: true })
})
// --- Wetter-Icon-Presets (Code→Icon-Tabellen) ---
// Jede API kodiert Wetter anders → keine feste Zuordnung, sondern editierbare Tabellen.
// Ein Preset wird beim ersten Start mitgeliefert: Open-Meteo (WMO 4677). icon/iconNight = Hex-Code
// der Schrift „Weather Icons"; iconNight optional (sonst gilt icon rund um die Uhr).
const ICON_PRESETS_FILE = path.join(DATA_DIR, 'icon-presets.json')
const OPEN_METEO_PRESET = {
id: 'open-meteo-wmo',
name: 'Open-Meteo (WMO)',
codePath: 'current.weather_code',
isDayPath: 'current.is_day',
entries: [
{ code: '0', icon: 'f00d', iconNight: 'f02e' }, // klar
{ code: '1', icon: 'f00c', iconNight: 'f081' }, // überwiegend klar
{ code: '2', icon: 'f002', iconNight: 'f086' }, // teilweise bewölkt
{ code: '3', icon: 'f013' }, // bedeckt
{ code: '45', icon: 'f014' }, { code: '48', icon: 'f014' }, // Nebel
{ code: '51', icon: 'f01c' }, { code: '53', icon: 'f01c' }, { code: '55', icon: 'f01a' }, // Niesel
{ code: '56', icon: 'f0b5' }, { code: '57', icon: 'f0b5' }, // gefrierender Niesel
{ code: '61', icon: 'f019' }, { code: '63', icon: 'f019' }, { code: '65', icon: 'f019' }, // Regen
{ code: '66', icon: 'f0b5' }, { code: '67', icon: 'f0b5' }, // gefrierender Regen
{ code: '71', icon: 'f01b' }, { code: '73', icon: 'f01b' }, { code: '75', icon: 'f01b' }, { code: '77', icon: 'f01b' }, // Schnee
{ code: '80', icon: 'f01a' }, { code: '81', icon: 'f01a' }, { code: '82', icon: 'f01a' }, // Regenschauer
{ code: '85', icon: 'f01b' }, { code: '86', icon: 'f01b' }, // Schneeschauer
{ code: '95', icon: 'f01e' }, { code: '96', icon: 'f01e' }, { code: '99', icon: 'f01e' }, // Gewitter
],
}
// Seed nur, wenn die Datei fehlt (Nutzer darf das Preset danach ändern/löschen)
if (!fs.existsSync(ICON_PRESETS_FILE)) writeJson(ICON_PRESETS_FILE, [OPEN_METEO_PRESET])
app.get('/api/icon-presets', (req, res) => res.json(readJson(ICON_PRESETS_FILE, [])))
app.post('/api/icon-presets', (req, res) => {
const { id, name, codePath, isDayPath, entries } = req.body || {}
if (!name || !Array.isArray(entries)) return res.status(400).json({ error: 'name + entries required' })
const list = readJson(ICON_PRESETS_FILE, [])
const pid = id || ('ip' + Date.now().toString(36))
const idx = list.findIndex(p => p.id === pid)
const entry = { id: pid, name, codePath: codePath || '', isDayPath: isDayPath || '', entries, updatedAt: new Date().toISOString() }
if (idx >= 0) list[idx] = entry; else list.push(entry)
writeJson(ICON_PRESETS_FILE, list)
res.json(entry)
})
app.delete('/api/icon-presets/:id', (req, res) => {
const list = readJson(ICON_PRESETS_FILE, []).filter(p => p.id !== req.params.id)
writeJson(ICON_PRESETS_FILE, list)
res.json({ ok: true })
})
// --- External APIs ---
app.get('/api/external-apis', (req, res) => res.json(readJson(APIS_FILE, [])))
app.post('/api/external-apis', (req, res) => {
writeJson(APIS_FILE, req.body)
res.json({ ok: true })
})
// --- API-Proxy: holt eine REGISTRIERTE externe API serverseitig ab (Header/Key aus apis.json,
// löst CORS; Key bleibt aus dem Browser). Allowlist gegen apis.json + SSRF-Guard verhindern
// Open-Proxy/Zugriff aufs interne Netz.
function isBlockedHost(host) {
const h = (host || '').toLowerCase().replace(/^\[|\]$/g, '')
if (!h || h === 'localhost' || h === '0.0.0.0' || h === '::1') return true
if (/^127\./.test(h) || /^10\./.test(h) || /^192\.168\./.test(h) || /^169\.254\./.test(h)) return true
if (/^172\.(1[6-9]|2\d|3[01])\./.test(h)) return true
if (/^(fc|fd)[0-9a-f]{2}:/.test(h)) return true // fc00::/7 (private IPv6)
return false
}
// Antwort-Cache je URL. Ohne ihn ruft JEDE Ebene (Temperatur, Wind, Sonne, Himmel, Bild …) und
// JEDER Client (Editor + /clock) die API einzeln ab → Tageslimits sind schnell erschöpft.
// Alle teilen sich hier eine Antwort; parallele Anfragen werden gebündelt (Dedupe).
const PROXY_TTL_MS = 5 * 60 * 1000 // Wetter ändert sich nicht sekündlich
const PROXY_FAIL_MS = 60 * 1000 // nach einem Fehler (z.B. Tageslimit) kurz nicht erneut anfragen
const proxyCache = new Map() // url -> { ts, data }
const proxyInflight = new Map() // url -> Promise
const proxyFail = new Map() // url -> { ts, msg }
app.post('/api/proxy', async (req, res) => {
const url = req.body && req.body.url
if (typeof url !== 'string') return res.status(400).json({ error: 'url fehlt' })
let parsed
try { parsed = new URL(url) } catch { return res.status(400).json({ error: 'ungültige url' }) }
if (!/^https?:$/.test(parsed.protocol)) return res.status(400).json({ error: 'nur http/https erlaubt' })
if (isBlockedHost(parsed.hostname)) return res.status(403).json({ error: 'host nicht erlaubt' })
// Allowlist: nur in apis.json registrierte URLs dürfen geproxied werden
const api = readJson(APIS_FILE, []).find(a => a.url === url)
if (!api) return res.status(403).json({ error: 'api nicht registriert' })
// Tatsächlicher Abruf-Takt: je API einstellbar (refreshInterval in Sekunden), sonst 5 Minuten
const ttlMs = Math.max(5, Number(api.refreshInterval) || (PROXY_TTL_MS / 1000)) * 1000
const cached = proxyCache.get(api.url)
if (cached && Date.now() - cached.ts < ttlMs) return res.json(cached.data)
// Nach einem Fehlschlag (z.B. Tageslimit) kurz gar nicht erst erneut anfragen
const failed = proxyFail.get(api.url)
if (failed && Date.now() - failed.ts < PROXY_FAIL_MS) {
if (cached) return res.json(cached.data) // letzte bekannte Antwort
return res.status(502).json({ error: failed.msg })
}
let pending = proxyInflight.get(api.url)
if (!pending) {
pending = (async () => {
const r = await fetch(api.url, {
method: api.method || 'GET',
headers: api.headers || {},
signal: AbortSignal.timeout(10000),
})
const text = await r.text()
if (!r.ok) throw new Error(`upstream HTTP ${r.status}: ${text.slice(0, 200)}`)
let data
try { data = JSON.parse(text) } catch { throw new Error('Antwort ist kein JSON') }
// Manche APIs (z.B. open-meteo) melden Limits als JSON mit HTTP 200 — nicht als gültig cachen
if (data && data.error === true) throw new Error(String(data.reason || 'API-Fehler'))
proxyCache.set(api.url, { ts: Date.now(), data })
proxyFail.delete(api.url)
return data
})()
proxyInflight.set(api.url, pending)
pending.catch(() => {}).finally(() => proxyInflight.delete(api.url))
}
try {
return res.json(await pending)
} catch (e) {
const msg = String((e && e.message) || e)
proxyFail.set(api.url, { ts: Date.now(), msg })
// Bei Upstream-Fehler (z.B. Limit erreicht) notfalls die letzte bekannte Antwort liefern
const stale = proxyCache.get(api.url)
if (stale) return res.json(stale.data)
return res.status(502).json({ error: msg })
}
})
// --- System / Performance ---
const os = require('os')
let lastCpu = process.cpuUsage()
let lastCpuTime = Date.now()
app.get('/api/system', (req, res) => {
const mem = process.memoryUsage()
const now = Date.now()
const cpu = process.cpuUsage(lastCpu)
const elapsed = (now - lastCpuTime) * 1000 // µs
const cpuPercent = elapsed > 0 ? Math.min(100, ((cpu.user + cpu.system) / elapsed) * 100) : 0
lastCpu = process.cpuUsage()
lastCpuTime = now
let clocks = 0
wss.clients.forEach(c => { if (c.readyState === WebSocket.OPEN && c.role === 'clock') clocks++ })
res.json({
nodeRssMb: Math.round(mem.rss / 1048576),
nodeHeapMb: Math.round(mem.heapUsed / 1048576),
cpuPercent: Math.round(cpuPercent * 10) / 10,
uptimeSec: Math.round(process.uptime()),
sysTotalMemMb: Math.round(os.totalmem() / 1048576),
sysFreeMemMb: Math.round(os.freemem() / 1048576),
cpuCount: os.cpus().length,
connectedClocks: clocks,
wsClients: wss.clients.size,
})
})
// --- Fonts ---
app.get('/api/fonts', (req, res) => {
const fontsDir = path.join(__dirname, 'public', 'fonts')
if (!fs.existsSync(fontsDir)) return res.json([])
const files = fs.readdirSync(fontsDir).filter(f => /\.(ttf|otf|woff|woff2)$/i.test(f))
res.json(files.map(f => ({ file: f, name: f.replace(/\.[^.]+$/, '') })))
})
// --- Sounds ---
app.get('/api/sounds', (req, res) => {
const soundsDir = path.join(__dirname, 'public', 'sounds')
if (!fs.existsSync(soundsDir)) return res.json([])
const files = fs.readdirSync(soundsDir).filter(f => /\.(mp3|wav|ogg|m4a|aac|flac)$/i.test(f))
res.json(files.map(f => ({ file: f, url: `/sounds/${f}`, name: f.replace(/\.[^.]+$/, '') })))
})
// --- Images (hochgeladene Bilder im Upload-Verzeichnis) ---
app.get('/api/images', (req, res) => {
const root = path.join(__dirname, 'public', 'uploads')
if (!fs.existsSync(root)) return res.json([])
const out = []
const walk = (dir, rel) => {
let entries
try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
for (const e of entries) {
if (e.name.startsWith('.')) continue
const relPath = rel ? `${rel}/${e.name}` : e.name
if (e.isDirectory()) {
walk(path.join(dir, e.name), relPath)
} else if (/\.(png|jpe?g|gif|webp|svg|bmp|avif)$/i.test(e.name)) {
// URL pro Segment encodieren (Leerzeichen/Sonderzeichen in Ordner-/Dateinamen)
const urlPath = relPath.split('/').map(encodeURIComponent).join('/')
out.push({ file: e.name, url: `/uploads/${urlPath}`, name: e.name.replace(/\.[^.]+$/, ''), folder: rel })
}
}
}
walk(root, '')
res.json(out)
})
// Nur die Ordnerstruktur unter public/uploads — auch LEERE Ordner, die /api/images
// nicht liefern kann (die Route listet Dateien). Für Ordner-Auswahlfelder beim Upload.
app.get('/api/image-folders', (req, res) => {
const root = path.join(__dirname, 'public', 'uploads')
if (!fs.existsSync(root)) return res.json([])
const out = []
const walk = (dir, rel, depth) => {
if (depth > 3) return
let entries
try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
for (const e of entries) {
if (!e.isDirectory() || e.name.startsWith('.')) continue
const relPath = rel ? `${rel}/${e.name}` : e.name
out.push(relPath)
walk(path.join(dir, e.name), relPath, depth + 1)
}
}
walk(root, '', 1)
res.json(out.sort())
})
// --- Upload ---
// Erlaubte Dateiendungen je Upload-Typ — alles andere wird abgelehnt (auch im LAN
// soll niemand HTML/Skripte in ausgelieferte Ordner legen können)
const UPLOAD_EXT = {
image: /\.(png|jpe?g|gif|webp|svg|bmp|avif)$/i,
font: /\.(ttf|otf|woff|woff2)$/i,
sound: /\.(mp3|wav|ogg|m4a|aac|flac)$/i,
}
// Optionaler Unterordner beim Upload: pro Segment säubern, max. 3 Ebenen, keine '.'/'..'
function safeSubfolder(folder) {
if (!folder || typeof folder !== 'string') return []
return folder.split(/[/\\]/)
.map(s => s.trim())
// Erst verwerfen, dann säubern — sonst würde aus '..' ein gültiges '__'
.filter(s => s && s !== '.' && s !== '..')
.map(s => s.replace(/[^a-zA-Z0-9 _-]/g, '_'))
// Segmente ohne jedes Schriftzeichen ergeben keinen sinnvollen Ordnernamen
.filter(s => /[a-zA-Z0-9]/.test(s) && s.length <= 40)
.slice(0, 3)
}
app.post('/api/upload', (req, res) => {
const { filename, data, type = 'image', folder } = req.body
if (!filename || !data) return res.status(400).json({ error: 'Missing filename or data' })
const dirs = {
font: ['public/fonts', '/fonts'],
sound: ['public/sounds', '/sounds'],
image: ['public/uploads', '/uploads'],
}
if (!dirs[type]) return res.status(400).json({ error: 'Invalid type' })
const safe = path.basename(filename).replace(/[^a-zA-Z0-9._-]/g, '_')
if (!UPLOAD_EXT[type].test(safe)) return res.status(400).json({ error: 'File type not allowed' })
const [dirRel, urlBase] = dirs[type]
const base = path.join(__dirname, ...dirRel.split('/'))
const segs = safeSubfolder(folder)
const dir = segs.length ? path.join(base, ...segs) : base
// Nach dem Zusammensetzen prüfen, dass der Pfad das erlaubte Verzeichnis nicht verlässt
const rel = path.relative(base, dir)
if (rel.startsWith('..') || path.isAbsolute(rel)) return res.status(400).json({ error: 'Invalid folder' })
const urlPrefix = segs.length ? '/' + segs.map(encodeURIComponent).join('/') : ''
try {
fs.mkdirSync(dir, { recursive: true })
} catch (e) {
return res.status(500).json({ error: 'Folder failed: ' + e.message })
}
try {
const base64 = data.includes(',') ? data.split(',')[1] : data
const buf = Buffer.from(base64, 'base64')
// SVG darf kein Skript enthalten (würde beim Ausliefern im Browser laufen)
if (/\.svg$/i.test(safe)) {
const txt = buf.toString('utf8')
if (/<script|javascript:|on\w+\s*=/i.test(txt)) {
return res.status(400).json({ error: 'SVG with scripts not allowed' })
}
}
fs.writeFileSync(path.join(dir, safe), buf)
res.json({ url: `${urlBase}${urlPrefix}/${safe}`, filename: safe, folder: segs.join('/') })
} catch (e) {
res.status(500).json({ error: 'Write failed: ' + e.message })
}
})
// SPA fallback
app.get(/^(?!\/api).*/, (req, res) => {
const dist = path.join(__dirname, 'client', 'dist', 'index.html')
if (fs.existsSync(dist)) {
res.sendFile(dist)
} else {
res.send('<h2>WallUI Lab — client not built yet. Run: cd client && npm install && npm run build</h2>')
}
})
server.listen(PORT, () => console.log(`WallUI Lab running on http://localhost:${PORT}`))