iobroker.agent-dvr 0.4.2 → 0.5.0

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