iobroker.agent-dvr 0.4.3 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/web.js CHANGED
@@ -17,8 +17,7 @@ const MIME = {
17
17
  '.json': 'application/json',
18
18
  };
19
19
 
20
- const WWW = path.join(__dirname, '..', 'www');
21
- const ROUTE = 'agent-dvr';
20
+ const WWW = path.join(__dirname, '..', 'www');
22
21
 
23
22
  class AgentDvrWeb {
24
23
  constructor(server, webSettings, adapter, instanceSettings, app) {
@@ -26,8 +25,22 @@ class AgentDvrWeb {
26
25
  this.adapter = adapter;
27
26
 
28
27
  const ns = instanceSettings ? instanceSettings._id.replace('system.adapter.', '') : 'agent-dvr.0';
28
+ const ROUTE = ns;
29
+ this._route = ns;
29
30
  const native = (instanceSettings && instanceSettings.native) ? instanceSettings.native : {};
30
31
 
32
+ // Keep native in sync — iobroker.web caches it at startup, so when the
33
+ // user saves adapter settings, the old values would stick until web restarts.
34
+ // Subscribing to object changes fixes this without a restart.
35
+ adapter.subscribeForeignObjects('system.adapter.' + ns);
36
+ adapter.on('objectChange', (id, obj) => {
37
+ if (id !== 'system.adapter.' + ns || !obj || !obj.native) return;
38
+ Object.assign(native, obj.native);
39
+ this._authHeader = (native.user || native.pass)
40
+ ? 'Basic ' + Buffer.from((native.user || '') + ':' + (native.pass || '')).toString('base64')
41
+ : null;
42
+ });
43
+
31
44
  // Cache auth header for proxy endpoints
32
45
  this._authHeader = (native.user || native.pass)
33
46
  ? 'Basic ' + Buffer.from((native.user || '') + ':' + (native.pass || '')).toString('base64')
@@ -49,7 +62,8 @@ class AgentDvrWeb {
49
62
  adapter.getForeignStatesAsync(ns + '.cam_*.status.alerted'),
50
63
  adapter.getForeignStatesAsync(ns + '.cam_*.data.width'),
51
64
  adapter.getForeignStatesAsync(ns + '.cam_*.data.height'),
52
- ]).then(([nameStates, mjpegStates, snapStates, onlineStates, ptzStates, recStates, detStates, alertStates, widthStates, heightStates]) => {
65
+ adapter.getForeignStatesAsync(ns + '.cam_*.color'),
66
+ ]).then(([nameStates, mjpegStates, snapStates, onlineStates, ptzStates, recStates, detStates, alertStates, widthStates, heightStates, colorStates]) => {
53
67
  const cameras = {};
54
68
 
55
69
  Object.entries(nameStates || {}).forEach(([id, state]) => {
@@ -105,6 +119,11 @@ class AgentDvrWeb {
105
119
  if (cameras[camKey]) cameras[camKey].alerted = !!(state && state.val);
106
120
  });
107
121
 
122
+ Object.entries(colorStates || {}).forEach(([id, state]) => {
123
+ const camKey = id.slice(ns.length + 1).split('.')[0];
124
+ if (cameras[camKey] && state && state.val) cameras[camKey].color = String(state.val);
125
+ });
126
+
108
127
  // Fallback URLs if enableUrls was off
109
128
  if (base) {
110
129
  Object.values(cameras).forEach(cam => {
@@ -152,9 +171,12 @@ class AgentDvrWeb {
152
171
  app.get('/' + ROUTE + '/api/config', (req, res) => {
153
172
  res.setHeader('Content-Type', 'application/json');
154
173
  res.end(JSON.stringify({
174
+ dashMaxRec: native.dashMaxRec || 200,
175
+ dashEnableRecordings: native.dashEnableRecordings !== false,
155
176
  dashDefaultView: native.dashDefaultView || 'live',
156
177
  dashShowOffline: native.dashShowOffline !== false,
157
178
  dashGridCols: native.dashGridCols || 0,
179
+ dashTileAspect: native.dashTileAspect || '16/9',
158
180
  dashBtnsVisible: !!native.dashBtnsVisible,
159
181
  dashRefreshSec: native.dashRefreshSec || 60,
160
182
  dashStreamReconnect: native.dashStreamReconnect !== false,
@@ -318,9 +340,37 @@ class AgentDvrWeb {
318
340
  }
319
341
  adapter.getForeignStateAsync(ns + '.' + camKey + '.events.json')
320
342
  .then(state => {
321
- const json = (state && state.val) ? String(state.val) : '[]';
343
+ const raw = (state && state.val) ? String(state.val) : '[]';
344
+ let items;
345
+ try { items = JSON.parse(raw); } catch (_) { items = []; }
346
+ if (Array.isArray(items)) {
347
+ items = items.map(rec => {
348
+ const out = Object.assign({}, rec);
349
+ // Always proxy video through /api/media to strip Content-Disposition: attachment
350
+ // and normalise the MIME type — required for inline <video> playback
351
+ if (typeof out.video === 'string' && out.video.startsWith('http')) {
352
+ try {
353
+ const u = new URL(out.video);
354
+ const oid = u.searchParams.get('oid');
355
+ const fn = u.searchParams.get('fn');
356
+ if (oid && fn) out.video = '/' + ROUTE + '/api/media?oid=' + encodeURIComponent(oid) + '&fn=' + encodeURIComponent(fn);
357
+ } catch (_) { /* keep original */ }
358
+ }
359
+ if (!native.enableStreamProxy) return out;
360
+ // When stream proxy is on, also proxy thumbnails
361
+ if (typeof out.thumb === 'string' && out.thumb.startsWith('http')) {
362
+ try {
363
+ const u = new URL(out.thumb);
364
+ const oid = u.searchParams.get('oid');
365
+ const fn = u.searchParams.get('fn');
366
+ if (oid && fn) out.thumb = '/' + ROUTE + '/api/thumb?oid=' + encodeURIComponent(oid) + '&fn=' + encodeURIComponent(fn);
367
+ } catch (_) { /* keep original */ }
368
+ }
369
+ return out;
370
+ });
371
+ }
322
372
  res.setHeader('Content-Type', 'application/json');
323
- res.end(json);
373
+ res.end(JSON.stringify(items));
324
374
  })
325
375
  .catch(err => {
326
376
  adapter.log.warn('[agent-dvr] /api/recordings error: ' + err.message);
@@ -328,6 +378,199 @@ class AgentDvrWeb {
328
378
  });
329
379
  });
330
380
 
381
+ // ── Delete recording (proxied to AgentDVR, requires v7.7.8.0+) ───────
382
+ app.get('/' + ROUTE + '/api/deleterecording', (req, res) => {
383
+ const base = (native.serverIp && native.port) ? 'http://' + native.serverIp + ':' + native.port : '';
384
+ if (!base) { res.status(503).json({ error: 'AgentDVR not configured' }); return; }
385
+ const oid = String(req.query.oid || '');
386
+ const fn = String(req.query.fn || '');
387
+ const camKey = String(req.query.camKey || '');
388
+ if (!oid || !/^\d+$/.test(oid) || !fn) { res.status(400).json({ error: 'invalid params' }); return; }
389
+ const url = base + '/command/deleterecording?oid=' + oid + '&ot=2&fn=' + encodeURIComponent(fn);
390
+ let target;
391
+ try { target = new URL(url); } catch (_) { res.status(500).json({ error: 'invalid url' }); return; }
392
+ const mod = target.protocol === 'https:' ? https : http;
393
+ const headers = {};
394
+ if (this._authHeader) headers['Authorization'] = this._authHeader;
395
+ let body = '';
396
+ const upReq = mod.get({ hostname: target.hostname, port: target.port, path: target.pathname + target.search, headers }, upstream => {
397
+ upstream.setEncoding('utf8');
398
+ upstream.on('data', chunk => { body += chunk; });
399
+ upstream.on('end', () => {
400
+ // On success, immediately update events.json to remove the deleted entry
401
+ // so the dashboard doesn't show it again on the next state-change refresh.
402
+ let data;
403
+ try { data = JSON.parse(body || '{}'); } catch (_) { data = {}; }
404
+ const ok = !data.error && (!data.status || data.status === 'ok');
405
+ if (ok && camKey && /^cam_[a-zA-Z0-9_-]+$/.test(camKey)) {
406
+ adapter.getForeignStateAsync(ns + '.' + camKey + '.events.json')
407
+ .then(state => {
408
+ const raw = (state && state.val) ? String(state.val) : '[]';
409
+ let items;
410
+ try { items = JSON.parse(raw); } catch (_) { items = []; }
411
+ if (Array.isArray(items)) {
412
+ const updated = items.filter(item => item.fn !== fn);
413
+ if (updated.length !== items.length) {
414
+ return adapter.setForeignStateAsync(
415
+ ns + '.' + camKey + '.events.json',
416
+ { val: JSON.stringify(updated), ack: true });
417
+ }
418
+ }
419
+ })
420
+ .catch(() => { /* non-critical — adapter will fix on next poll */ });
421
+ }
422
+ res.setHeader('Content-Type', 'application/json');
423
+ res.status(upstream.statusCode || 200).end(body || '{}');
424
+ });
425
+ upstream.on('error', () => { if (!res.headersSent) res.status(502).json({ error: 'upstream error' }); });
426
+ });
427
+ upReq.setTimeout(10000, () => upReq.destroy());
428
+ upReq.on('error', () => { if (!res.headersSent) res.status(502).json({ error: 'connection failed' }); });
429
+ });
430
+
431
+ // ── Webhook — triggers a full adapter poll ────────────────────────────
432
+ app.get('/' + ROUTE + '/webhook', (req, res) => {
433
+ adapter.setForeignStateAsync(ns + '.system.control.refresh', { val: true, ack: false })
434
+ .then(() => res.json({ ok: true }))
435
+ .catch(err => res.status(500).json({ error: err.message }));
436
+ });
437
+
438
+ // ── System stats ─────────────────────────────────────────────────────
439
+ app.get('/' + ROUTE + '/api/systemstats', (req, res) => {
440
+ const base = (native.serverIp && native.port) ? 'http://' + native.serverIp + ':' + native.port : '';
441
+ if (!base) { res.status(503).json({ error: 'AgentDVR not configured' }); return; }
442
+ const url = base + '/command/getSystemStats';
443
+ let target;
444
+ try { target = new URL(url); } catch (_) { res.status(500).json({ error: 'invalid url' }); return; }
445
+ const mod = target.protocol === 'https:' ? https : http;
446
+ const headers = {};
447
+ if (this._authHeader) headers['Authorization'] = this._authHeader;
448
+ let body = '';
449
+ const upReq = mod.get({ hostname: target.hostname, port: target.port, path: target.pathname + target.search, headers }, upstream => {
450
+ upstream.setEncoding('utf8');
451
+ upstream.on('data', chunk => { body += chunk; });
452
+ upstream.on('end', () => {
453
+ res.setHeader('Content-Type', 'application/json');
454
+ res.status(upstream.statusCode || 200).end(body || '{}');
455
+ });
456
+ upstream.on('error', () => { if (!res.headersSent) res.status(502).json({ error: 'upstream error' }); });
457
+ });
458
+ upReq.setTimeout(5000, () => upReq.destroy());
459
+ upReq.on('error', () => { if (!res.headersSent) res.status(502).json({ error: 'connection failed' }); });
460
+ });
461
+
462
+ // ── PTZ preset list ──────────────────────────────────────────────────
463
+ app.get('/' + ROUTE + '/api/ptzpresets', (req, res) => {
464
+ const base = (native.serverIp && native.port) ? 'http://' + native.serverIp + ':' + native.port : '';
465
+ if (!base) { res.status(503).json({ error: 'AgentDVR not configured' }); return; }
466
+ const oid = String(req.query.oid || '');
467
+ if (!oid || !/^\d+$/.test(oid)) { res.status(400).json({ error: 'invalid params' }); return; }
468
+ const url = base + '/command/ptzpresets?oid=' + oid + '&ot=2';
469
+ let target;
470
+ try { target = new URL(url); } catch (_) { res.status(500).json({ error: 'invalid url' }); return; }
471
+ const mod = target.protocol === 'https:' ? https : http;
472
+ const headers = {};
473
+ if (this._authHeader) headers['Authorization'] = this._authHeader;
474
+ let body = '';
475
+ const upReq = mod.get({ hostname: target.hostname, port: target.port, path: target.pathname + target.search, headers }, upstream => {
476
+ upstream.setEncoding('utf8');
477
+ upstream.on('data', chunk => { body += chunk; });
478
+ upstream.on('end', () => {
479
+ res.setHeader('Content-Type', 'application/json');
480
+ res.status(upstream.statusCode || 200).end(body || '{}');
481
+ });
482
+ upstream.on('error', () => { if (!res.headersSent) res.status(502).json({ error: 'upstream error' }); });
483
+ });
484
+ upReq.setTimeout(5000, () => upReq.destroy());
485
+ upReq.on('error', () => { if (!res.headersSent) res.status(502).json({ error: 'connection failed' }); });
486
+ });
487
+
488
+ // ── PTZ preset navigate ───────────────────────────────────────────────
489
+ app.get('/' + ROUTE + '/api/ptzpreset', (req, res) => {
490
+ const base = (native.serverIp && native.port) ? 'http://' + native.serverIp + ':' + native.port : '';
491
+ if (!base) { res.status(503).json({ error: 'AgentDVR not configured' }); return; }
492
+ const oid = String(req.query.oid || '');
493
+ const preset = String(req.query.preset || '');
494
+ if (!oid || !/^\d+$/.test(oid) || !preset) { res.status(400).json({ error: 'invalid params' }); return; }
495
+ const url = base + '/command/ptzpreset?oid=' + oid + '&ot=2&preset=' + encodeURIComponent(preset);
496
+ let target;
497
+ try { target = new URL(url); } catch (_) { res.status(500).json({ error: 'invalid url' }); return; }
498
+ const mod = target.protocol === 'https:' ? https : http;
499
+ const headers = {};
500
+ if (this._authHeader) headers['Authorization'] = this._authHeader;
501
+ let body = '';
502
+ const upReq = mod.get({ hostname: target.hostname, port: target.port, path: target.pathname + target.search, headers }, upstream => {
503
+ upstream.setEncoding('utf8');
504
+ upstream.on('data', chunk => { body += chunk; });
505
+ upstream.on('end', () => {
506
+ res.setHeader('Content-Type', 'application/json');
507
+ res.status(upstream.statusCode || 200).end(body || '{}');
508
+ });
509
+ upstream.on('error', () => { if (!res.headersSent) res.status(502).json({ error: 'upstream error' }); });
510
+ });
511
+ upReq.setTimeout(5000, () => upReq.destroy());
512
+ upReq.on('error', () => { if (!res.headersSent) res.status(502).json({ error: 'connection failed' }); });
513
+ });
514
+
515
+ // ── Recording thumbnail proxy (optional: enableStreamProxy) ──────────
516
+ app.get('/' + ROUTE + '/api/thumb', (req, res) => {
517
+ const base = (native.serverIp && native.port) ? 'http://' + native.serverIp + ':' + native.port : '';
518
+ if (!base) { res.status(503).end('AgentDVR not configured'); return; }
519
+ const oid = String(req.query.oid || '');
520
+ const fn = String(req.query.fn || '');
521
+ if (!oid || !/^\d+$/.test(oid) || !fn) { res.status(400).end('invalid params'); return; }
522
+ const url = base + '/fileThumb.jpg?oid=' + oid + '&fn=' + encodeURIComponent(fn);
523
+ let target;
524
+ try { target = new URL(url); } catch (_) { res.status(500).end(); return; }
525
+ const mod = target.protocol === 'https:' ? https : http;
526
+ const headers = {};
527
+ if (this._authHeader) headers['Authorization'] = this._authHeader;
528
+ const upReq = mod.get({ hostname: target.hostname, port: target.port, path: target.pathname + target.search, headers }, upstream => {
529
+ res.setHeader('Content-Type', upstream.headers['content-type'] || 'image/jpeg');
530
+ res.setHeader('Cache-Control', 'max-age=86400');
531
+ upstream.pipe(res);
532
+ upstream.on('error', () => { if (!res.headersSent) res.status(502).end(); else res.end(); });
533
+ });
534
+ upReq.setTimeout(8000, () => upReq.destroy());
535
+ upReq.on('error', () => { if (!res.headersSent) res.status(502).end(); else res.end(); });
536
+ req.on('close', () => { try { upReq.destroy(); } catch (_) {} });
537
+ });
538
+
539
+ // ── Recording video proxy (optional: enableStreamProxy) ──────────────
540
+ app.get('/' + ROUTE + '/api/media', (req, res) => {
541
+ const base = (native.serverIp && native.port) ? 'http://' + native.serverIp + ':' + native.port : '';
542
+ if (!base) { res.status(503).end('AgentDVR not configured'); return; }
543
+ const oid = String(req.query.oid || '');
544
+ const fn = String(req.query.fn || '');
545
+ if (!oid || !/^\d+$/.test(oid) || !fn) { res.status(400).end('invalid params'); return; }
546
+ const url = base + '/streamFile.cgi?oid=' + oid + '&ot=2&fn=' + encodeURIComponent(fn);
547
+ let target;
548
+ try { target = new URL(url); } catch (_) { res.status(500).end(); return; }
549
+ const mod = target.protocol === 'https:' ? https : http;
550
+ const headers = {};
551
+ if (this._authHeader) headers['Authorization'] = this._authHeader;
552
+ // Forward Range header so the browser can seek in the video
553
+ if (req.headers['range']) headers['Range'] = req.headers['range'];
554
+ const upReq = mod.get({ hostname: target.hostname, port: target.port, path: target.pathname + target.search, headers }, upstream => {
555
+ const status = upstream.statusCode || 200;
556
+ // Normalise non-standard MIME type and never forward Content-Disposition
557
+ // so the browser plays the video inline instead of downloading it
558
+ const ct = (upstream.headers['content-type'] || 'video/mp4')
559
+ .replace(/video\/mkv\b/i, 'video/x-matroska');
560
+ res.setHeader('Content-Type', ct);
561
+ res.setHeader('Accept-Ranges', 'bytes');
562
+ if (upstream.headers['content-range']) res.setHeader('Content-Range', upstream.headers['content-range']);
563
+ if (upstream.headers['content-length']) res.setHeader('Content-Length', upstream.headers['content-length']);
564
+ res.setHeader('Cache-Control', 'no-cache');
565
+ res.status(status);
566
+ upstream.pipe(res);
567
+ upstream.on('error', () => { if (!res.headersSent) res.status(502).end(); else res.end(); });
568
+ });
569
+ upReq.setTimeout(0); // no timeout for potentially large video files
570
+ upReq.on('error', () => { if (!res.headersSent) res.status(502).end(); else res.end(); });
571
+ req.on('close', () => { try { upReq.destroy(); } catch (_) {} });
572
+ });
573
+
331
574
  // ── Static file handler ───────────────────────────────────────────────
332
575
  app.use('/' + ROUTE, (req, res) => {
333
576
  let rel = (req.url || '/').split('?')[0];
@@ -395,7 +638,7 @@ class AgentDvrWeb {
395
638
 
396
639
  welcomePage() {
397
640
  return {
398
- link: ROUTE + '/',
641
+ link: this._route + '/',
399
642
  name: 'AgentDVR',
400
643
  img: 'adapter/agent-dvr/agent-dvr.png',
401
644
  color: '#2196f3',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iobroker.agent-dvr",
3
- "version": "0.4.3",
3
+ "version": "0.5.1",
4
4
  "description": "Connects ioBroker to AgentDVR: auto-discovers cameras, mirrors all device values as data points, delivers real-time triggers on new recordings, and generates a responsive HTML gallery with optional search and tag filtering.",
5
5
  "author": {
6
6
  "name": "ipod86",