iobroker.agent-dvr 0.5.4 → 0.6.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/build/main.js CHANGED
@@ -24,6 +24,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
24
  var utils = __toESM(require("@iobroker/adapter-core"));
25
25
  var http = __toESM(require("node:http"));
26
26
  var https = __toESM(require("node:https"));
27
+ var path = __toESM(require("node:path"));
27
28
  var import_widget_i18n = require("./lib/widget-i18n");
28
29
  const CAM_COMMANDS = [
29
30
  { id: "record", path: "/command/record", params: ["oid", "ot"], name: "Start recording" },
@@ -284,6 +285,30 @@ function scan(){var roots=document.querySelectorAll('.advroot');for(var i=0;i<ro
284
285
  window.ADVscan=scan;scan();
285
286
  })();
286
287
  `.trim();
288
+ const ADV_BOOT_IMG = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
289
+ function advScriptBootstrap(scriptClass, scanFnName) {
290
+ return `<img alt="" src="${ADV_BOOT_IMG}" style="display:none" onload="(function(){if(window.${scanFnName}){window.${scanFnName}();return;}var c=document.querySelector('script.${scriptClass}');if(!c)return;var s=document.createElement('script');s.textContent=c.textContent;document.body.appendChild(s);})()">`;
291
+ }
292
+ const ADV_LIVE_REFRESH_CODE = `
293
+ (function(){
294
+ function initRoot(root){
295
+ if(root.__advLive)return;
296
+ root.__advLive=1;
297
+ var imgs=root.querySelectorAll('.advlivethumb');
298
+ for(var i=0;i<imgs.length;i++)(function(img){
299
+ var base=img.getAttribute('data-base');
300
+ var sec=parseInt(img.getAttribute('data-refresh'),10)||0;
301
+ if(!base||sec<=0)return;
302
+ setInterval(function(){img.src=base+'&ts='+Date.now();},sec*1000);
303
+ })(imgs[i]);
304
+ }
305
+ function scan(){var roots=document.querySelectorAll('.advgrid');for(var i=0;i<roots.length;i++)initRoot(roots[i]);}
306
+ window.ADVLiveScan=scan;scan();
307
+ })();
308
+ `.trim();
309
+ function advLiveRefreshScript() {
310
+ return `<script type="text/plain" class="advlivecode">${ADV_LIVE_REFRESH_CODE}</script>${advScriptBootstrap("advlivecode", "ADVLiveScan")}`;
311
+ }
287
312
  class AgentDvr extends utils.Adapter {
288
313
  pollTimer = void 0;
289
314
  pollBusy = false;
@@ -297,9 +322,15 @@ class AgentDvr extends utils.Adapter {
297
322
  ptzActive = /* @__PURE__ */ new Map();
298
323
  ptzPresetNames = /* @__PURE__ */ new Map();
299
324
  widgetSig = {};
325
+ widgetLastWrite = {};
300
326
  profileSig = "";
301
327
  lastCamNames = [];
302
328
  lastEventFn = {};
329
+ // tags per recent recording — AgentDVR often adds the AI tag (e.g. "people")
330
+ // only after the recording was first listed, so late tags must still pulse
331
+ eventTagsSeen = {};
332
+ // last webhook alert pulse per camera — AgentDVR often calls the action twice per motion
333
+ webhookLast = {};
303
334
  camAspect = {};
304
335
  devById = /* @__PURE__ */ new Map();
305
336
  eventBusy = {};
@@ -448,6 +479,10 @@ class AgentDvr extends utils.Adapter {
448
479
  return;
449
480
  }
450
481
  const relId = this.getRelId(id);
482
+ if (relId === "system.webhook") {
483
+ this.onWebhook(state.val).catch((e) => this.log.warn(`Webhook error: ${e.message}`));
484
+ return;
485
+ }
451
486
  const entry = this.registry.get(relId);
452
487
  if (entry) {
453
488
  this.runCommand(relId, entry, state.val).catch(
@@ -459,7 +494,7 @@ class AgentDvr extends utils.Adapter {
459
494
  getRelId(fullId) {
460
495
  return fullId.startsWith(`${this.namespace}.`) ? fullId.slice(this.namespace.length + 1) : fullId;
461
496
  }
462
- apiGet(path) {
497
+ apiGet(path2) {
463
498
  return new Promise((resolve) => {
464
499
  var _a;
465
500
  const rawTimeout = (_a = this.config.httpTimeoutMs) != null ? _a : 8e3;
@@ -470,7 +505,7 @@ class AgentDvr extends utils.Adapter {
470
505
  const opts = {
471
506
  hostname: this.config.serverIp,
472
507
  port: this.config.port || 8090,
473
- path,
508
+ path: path2,
474
509
  method: "GET",
475
510
  timeout
476
511
  };
@@ -503,7 +538,7 @@ class AgentDvr extends utils.Adapter {
503
538
  }
504
539
  });
505
540
  }
506
- apiGetBuffer(path) {
541
+ apiGetBuffer(path2) {
507
542
  return new Promise((resolve) => {
508
543
  var _a;
509
544
  const rawTimeout = (_a = this.config.httpTimeoutMs) != null ? _a : 8e3;
@@ -514,7 +549,7 @@ class AgentDvr extends utils.Adapter {
514
549
  const opts = {
515
550
  hostname: this.config.serverIp,
516
551
  port: this.config.port || 8090,
517
- path,
552
+ path: path2,
518
553
  method: "GET",
519
554
  timeout
520
555
  };
@@ -709,6 +744,20 @@ class AgentDvr extends utils.Adapter {
709
744
  await this.writeLeaf("system.lastUpdate", "");
710
745
  await this.writeLeaf("system.lastPoll", 0);
711
746
  await this.writeLeaf("system.cameraCount", 0);
747
+ if (!this.ensuredFolders.has("system.webhook")) {
748
+ await this.setObjectNotExistsAsync("system.webhook", {
749
+ type: "state",
750
+ common: {
751
+ name: "Last webhook call (JSON)",
752
+ type: "string",
753
+ role: "json",
754
+ read: true,
755
+ write: true
756
+ },
757
+ native: {}
758
+ });
759
+ this.ensuredFolders.add("system.webhook");
760
+ }
712
761
  if (this.config.enableSystemControls) {
713
762
  await this.ensureFolder("system.control", "Control", "channel");
714
763
  for (const c of SYS_COMMANDS) {
@@ -756,6 +805,130 @@ class AgentDvr extends utils.Adapter {
756
805
  this.log.debug(`cam ${d.oid} resolution ${wh[0]}x${wh[1]} -> AR ${this.camAspect[d.oid]}`);
757
806
  }
758
807
  }
808
+ // ---- webhook ----
809
+ // Written by the web extension (lib/web.js) when AgentDVR calls the webhook with ?oid={ID}.
810
+ // Pulses <cam>.events.webhook right away — before the poll — so scripts can grab a photo
811
+ // at the moment of the alert, then refreshes all data.
812
+ async onWebhook(val) {
813
+ var _a, _b, _c;
814
+ let q = {};
815
+ try {
816
+ q = JSON.parse(String(val != null ? val : "{}"));
817
+ } catch {
818
+ }
819
+ await this.setStateAsync("system.webhook", { val: String(val != null ? val : ""), ack: true });
820
+ const oid = `${(_a = q.oid) != null ? _a : ""}`;
821
+ const ot = `${(_b = q.ot) != null ? _b : "2"}`;
822
+ const dev = [...this.devById.values()].find((d) => String(d.oid) === oid && String(d.ot) === ot);
823
+ if (dev) {
824
+ const fid = this.deviceFolder(dev);
825
+ const key = `${ot}_${oid}`;
826
+ const cooldownMs = 2e4;
827
+ if (Date.now() - ((_c = this.webhookLast[key]) != null ? _c : 0) >= cooldownMs) {
828
+ this.webhookLast[key] = Date.now();
829
+ await this.ensureFlag(`${fid}.events.webhook`, "Webhook alert (AgentDVR action)");
830
+ await this.pulse(`${fid}.events.webhook`);
831
+ this.log.debug(`Webhook alert cam ${oid} \u2192 ${fid}.events.webhook`);
832
+ if (this.config.enableAlertPhotos !== false && dev.ot === 2) {
833
+ this.saveAlertPhoto(dev.oid, fid).catch(
834
+ (e) => this.log.warn(`Alert photo cam ${oid}: ${e.message}`)
835
+ );
836
+ }
837
+ } else {
838
+ this.log.debug(`Webhook alert cam ${oid} ignored (cooldown)`);
839
+ }
840
+ } else if (oid) {
841
+ this.log.debug(`Webhook: no device with oid ${oid} / ot ${ot}`);
842
+ }
843
+ if (this.pollBusy) {
844
+ this.scheduleRefresh();
845
+ } else {
846
+ await this.poll().catch((e) => this.log.warn(`Webhook refresh error: ${e.message}`));
847
+ }
848
+ }
849
+ // Keeps the last 3 alert photos per camera in the file storage (<namespace>/<fid>/grab1..3.jpg,
850
+ // grab1 = newest). ts1 is written last, so it is a safe trigger: the file is complete by then.
851
+ async saveAlertPhoto(oid, fid) {
852
+ var _a, _b;
853
+ const img = await this.apiGetBuffer(`/photo.jpg?oid=${oid}`);
854
+ if (!img.ok || !img.data) {
855
+ this.log.warn(`Alert photo cam ${oid} not fetched: ${(_a = img.error) != null ? _a : "empty response"}`);
856
+ return;
857
+ }
858
+ const ch = `${fid}.alertPhotos`;
859
+ if (!this.ensuredFolders.has(this.namespace)) {
860
+ await this.setForeignObjectNotExistsAsync(this.namespace, {
861
+ type: "meta",
862
+ common: { name: "Alert photos", type: "meta.user" },
863
+ native: {}
864
+ });
865
+ this.ensuredFolders.add(this.namespace);
866
+ }
867
+ if (!this.ensuredFolders.has(ch)) {
868
+ await this.ensureFolder(ch, "Alert photos", "channel");
869
+ for (let i = 1; i <= 3; i++) {
870
+ await this.setObjectNotExistsAsync(`${ch}.grab${i}`, {
871
+ type: "state",
872
+ common: {
873
+ name: `Alert photo ${i} (file path)`,
874
+ type: "string",
875
+ role: "text",
876
+ read: true,
877
+ write: false
878
+ },
879
+ native: {}
880
+ });
881
+ await this.setObjectNotExistsAsync(`${ch}.uri${i}`, {
882
+ type: "state",
883
+ common: {
884
+ name: `Alert photo ${i} (iobfile URI)`,
885
+ type: "string",
886
+ role: "text",
887
+ read: true,
888
+ write: false
889
+ },
890
+ native: {}
891
+ });
892
+ await this.setObjectNotExistsAsync(`${ch}.ts${i}`, {
893
+ type: "state",
894
+ common: {
895
+ name: `Alert photo ${i} (time)`,
896
+ type: "number",
897
+ role: "value.time",
898
+ read: true,
899
+ write: false
900
+ },
901
+ native: {}
902
+ });
903
+ }
904
+ this.ensuredFolders.add(ch);
905
+ }
906
+ for (let i = 2; i >= 1; i--) {
907
+ try {
908
+ const prev = await this.readFileAsync(this.namespace, `${fid}/grab${i}.jpg`);
909
+ await this.writeFileAsync(this.namespace, `${fid}/grab${i + 1}.jpg`, prev.file);
910
+ const ts = await this.getStateAsync(`${ch}.ts${i}`);
911
+ await this.setStateAsync(`${ch}.ts${i + 1}`, { val: (_b = ts == null ? void 0 : ts.val) != null ? _b : null, ack: true });
912
+ await this.setStateAsync(`${ch}.grab${i + 1}`, { val: this.alertPhotoPath(fid, i + 1), ack: true });
913
+ await this.setStateAsync(`${ch}.uri${i + 1}`, { val: this.alertPhotoUri(fid, i + 1), ack: true });
914
+ } catch {
915
+ }
916
+ }
917
+ await this.writeFileAsync(this.namespace, `${fid}/grab1.jpg`, img.data);
918
+ await this.setStateAsync(`${ch}.grab1`, { val: this.alertPhotoPath(fid, 1), ack: true });
919
+ await this.setStateAsync(`${ch}.uri1`, { val: this.alertPhotoUri(fid, 1), ack: true });
920
+ await this.setStateAsync(`${ch}.ts1`, { val: Date.now(), ack: true });
921
+ this.log.debug(`Alert photo cam ${oid} saved (${img.data.length} bytes)`);
922
+ }
923
+ // ioBroker file URI of a stored alert photo — resolved by telegram >= 6 directly from the file storage
924
+ alertPhotoUri(fid, n) {
925
+ return `iobfile://${this.namespace}/${fid}/grab${n}.jpg`;
926
+ }
927
+ // Absolute path of a stored alert photo, for consumers that need a local file (e.g. telegram).
928
+ // Only valid when the file storage lives on this host's disk (default jsonl/file DB).
929
+ alertPhotoPath(fid, n) {
930
+ return path.join(utils.getAbsoluteDefaultDataDir(), "files", this.namespace, fid, `grab${n}.jpg`);
931
+ }
759
932
  // ---- device folder name ----
760
933
  deviceFolder(d) {
761
934
  return `${d.ot === 1 ? "mic" : "cam"}_${sanitize(d.oid)}_${sanitize(d.name)}`;
@@ -957,6 +1130,19 @@ class AgentDvr extends utils.Adapter {
957
1130
  const ts = this.config.widgetThumbSize;
958
1131
  return ts && sizeMap[ts] ? sizeMap[ts] : this.config.widgetMinCol || 150;
959
1132
  }
1133
+ // Theme-Farben gelten gleichermassen fuer Aufnahmen- und Live-Widget (rein
1134
+ // optisch, nichts Aufnahmen-Spezifisches) - ein Helper statt die sechs Felder
1135
+ // an jeder Stelle zu wiederholen.
1136
+ widgetColors() {
1137
+ return {
1138
+ cardBg: this.config.widgetColorCardBg || void 0,
1139
+ tagBg: this.config.widgetColorTagBg || void 0,
1140
+ tagText: this.config.widgetColorTagText || void 0,
1141
+ accent: this.config.widgetColorAccent || void 0,
1142
+ modalBg: this.config.widgetColorModalBg || void 0,
1143
+ radius: this.config.widgetBorderRadius
1144
+ };
1145
+ }
960
1146
  async pruneStaleDevices(activeFolders) {
961
1147
  const allObjs = await this.getAdapterObjectsAsync();
962
1148
  const stale = [];
@@ -1011,14 +1197,7 @@ class AgentDvr extends utils.Adapter {
1011
1197
  }).join("");
1012
1198
  const gridClass = compact ? "advgrid advcompact" : "advgrid";
1013
1199
  const grid = items ? `<div class="${gridClass}">${items}</div>` : `<div class="advempty">${this.wt.noRecordings}</div>`;
1014
- const colors = {
1015
- cardBg: this.config.widgetColorCardBg || void 0,
1016
- tagBg: this.config.widgetColorTagBg || void 0,
1017
- tagText: this.config.widgetColorTagText || void 0,
1018
- accent: this.config.widgetColorAccent || void 0,
1019
- modalBg: this.config.widgetColorModalBg || void 0,
1020
- radius: this.config.widgetBorderRadius
1021
- };
1200
+ const colors = this.widgetColors();
1022
1201
  return `<style>${galleryCss(minCol, maxW, compact, colors)}</style>${grid}`;
1023
1202
  }
1024
1203
  buildGalleryHtmlJs(d, events) {
@@ -1055,53 +1234,61 @@ class AgentDvr extends utils.Adapter {
1055
1234
  const data = JSON.stringify({ items, live: null, cfg }).replace(/</g, "\\u003c");
1056
1235
  const boot = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
1057
1236
  const searchHtml = showSearch ? `<input class="advsearchjs" type="text" placeholder="${escHtml(this.wt.search)}">` : "";
1058
- const colors = {
1059
- cardBg: this.config.widgetColorCardBg || void 0,
1060
- tagBg: this.config.widgetColorTagBg || void 0,
1061
- tagText: this.config.widgetColorTagText || void 0,
1062
- accent: this.config.widgetColorAccent || void 0,
1063
- modalBg: this.config.widgetColorModalBg || void 0,
1064
- radius: this.config.widgetBorderRadius
1065
- };
1237
+ const colors = this.widgetColors();
1066
1238
  return `<style>${galleryCssJs(minCol, compact, colors)}</style><div class="advroot"><script type="application/json" class="advdata">${data}</script><div class="advbar">${searchHtml}<div class="advtagsjs"></div></div><div class="advgridjs"></div></div><script type="text/plain" class="advcode">${ADV_CLIENT_CODE}</script><img alt="" src="${boot}" style="display:none" onload="(function(){if(window.ADVscan){window.ADVscan();return;}var c=document.querySelector('script.advcode');if(!c)return;var s=document.createElement('script');s.textContent=c.textContent;document.body.appendChild(s);})()">`;
1067
1239
  }
1068
1240
  buildOverviewHtml(cams) {
1069
- const ts = Date.now();
1070
- const minCol = this.config.widgetMinCol || 150;
1241
+ const minCol = this.effectiveMinCol();
1071
1242
  const maxW = this.config.widgetMaxModalWidth || 900;
1243
+ const compact = !!this.config.widgetCompact;
1244
+ const colors = this.widgetColors();
1245
+ const jsMode = this.config.widgetLiveMode === "js";
1246
+ const refreshSec = Number(this.config.widgetLiveRefreshSec) || 0;
1072
1247
  const PAUSE_ATTR = ` onchange="if(!this.checked){var m=this.nextElementSibling.nextElementSibling,v=m&&m.querySelector('video');if(v){v.pause();}}"`;
1073
1248
  const tiles = cams.map((d) => {
1074
1249
  const oid = d.oid;
1075
1250
  const id = `advlive${sanitize(oid)}`;
1076
- const grab = `${this.baseUrl}/grab.jpg?oid=${oid}&ot=2&maintainAR=1&ts=${ts}`;
1251
+ const grabBase = `${this.baseUrl}/grab.jpg?oid=${oid}&ot=2&maintainAR=1`;
1252
+ const grab = `${grabBase}&ts=${Date.now()}`;
1077
1253
  const webm = `${this.baseUrl}/video.webm?oid=${oid}&ot=2`;
1078
1254
  const name = escHtml(d.name || `Camera ${oid}`);
1079
1255
  const arRaw = this.camAspect[oid] || this.config.widgetLiveAspect || "";
1080
1256
  const ar = arRaw ? String(arRaw).replace("/", " / ") : "";
1081
1257
  const fix = ar ? " advimgfix" : "";
1082
1258
  const arStyle = ar ? ` style="aspect-ratio:${ar}"` : "";
1083
- const inner = `<span class="advimg${fix}"${arStyle}><img src="${grab}" loading="lazy" alt=""><span class="advtag" style="top:5px;left:5px">&#9679; ${escHtml(this.wt.live)}</span><span class="advplay"></span></span><span class="advcap">${name}</span>`;
1084
- return `<input class="advlb" type="checkbox" id="${id}"${PAUSE_ATTR}><label class="advcell advthumb" for="${id}">${inner}</label><div class="advmodal"><label class="advbackdrop" for="${id}"></label><div class="advbox"><label class="advclose" for="${id}">&#10005;</label><video class="advvideo" controls preload="none" playsinline${arStyle} src="${webm}"></video><div class="advinfo">${name} &middot; Live</div></div></div>`;
1259
+ const videoArStyle = ar ? ` style="aspect-ratio:${ar};object-fit:fill"` : "";
1260
+ const imgAttrs = jsMode ? ` class="advlivethumb" data-base="${grabBase}" data-refresh="${refreshSec}"` : "";
1261
+ const inner = `<span class="advimg${fix}"${arStyle}><img${imgAttrs} src="${grab}" loading="lazy" alt=""><span class="advtag" style="top:5px;left:5px">&#9679; ${escHtml(this.wt.live)}</span><span class="advplay"></span></span><span class="advcap">${name}</span>`;
1262
+ return `<input class="advlb" type="checkbox" id="${id}"${PAUSE_ATTR}><label class="advcell advthumb" for="${id}">${inner}</label><div class="advmodal"><label class="advbackdrop" for="${id}"></label><div class="advbox"><label class="advclose" for="${id}">&#10005;</label><video class="advvideo" controls preload="none" playsinline${videoArStyle} src="${webm}"></video><div class="advinfo">${name} &middot; Live</div></div></div>`;
1085
1263
  }).join("");
1086
1264
  const grid = tiles ? `<div class="advgrid">${tiles}</div>` : `<div class="advempty">No cameras</div>`;
1087
- return `<style>${galleryCss(minCol, maxW)}</style>${grid}`;
1265
+ const script = jsMode && tiles ? advLiveRefreshScript() : "";
1266
+ return `<style>${galleryCss(minCol, maxW, compact, colors)}</style>${grid}${script}`;
1088
1267
  }
1089
1268
  buildSingleCamLiveHtml(d) {
1090
- const minCol = this.config.widgetMinCol || 150;
1269
+ const minCol = this.effectiveMinCol();
1091
1270
  const maxW = this.config.widgetMaxModalWidth || 900;
1271
+ const compact = !!this.config.widgetCompact;
1272
+ const colors = this.widgetColors();
1092
1273
  const PAUSE_ATTR = ` onchange="if(!this.checked){var m=this.nextElementSibling.nextElementSibling,v=m&&m.querySelector('video');if(v){v.pause();}}"`;
1274
+ const jsMode = this.config.widgetLiveMode === "js";
1275
+ const refreshSec = Number(this.config.widgetLiveRefreshSec) || 0;
1093
1276
  const oid = d.oid;
1094
1277
  const id = `advlive${sanitize(oid)}`;
1095
- const grab = `${this.baseUrl}/grab.jpg?oid=${oid}&ot=2&maintainAR=1&ts=${Date.now()}`;
1278
+ const grabBase = `${this.baseUrl}/grab.jpg?oid=${oid}&ot=2&maintainAR=1`;
1279
+ const grab = `${grabBase}&ts=${Date.now()}`;
1096
1280
  const webm = `${this.baseUrl}/video.webm?oid=${oid}&ot=2`;
1097
1281
  const name = escHtml(d.name || `Camera ${oid}`);
1098
1282
  const arRaw = this.camAspect[oid] || this.config.widgetLiveAspect || "";
1099
1283
  const ar = arRaw ? String(arRaw).replace("/", " / ") : "";
1100
1284
  const fix = ar ? " advimgfix" : "";
1101
1285
  const arStyle = ar ? ` style="aspect-ratio:${ar}"` : "";
1102
- const inner = `<span class="advimg${fix}"${arStyle}><img src="${grab}" loading="lazy" alt=""><span class="advtag" style="top:5px;left:5px">&#9679; ${escHtml(this.wt.live)}</span><span class="advplay"></span></span><span class="advcap">${name}</span>`;
1103
- const tile = `<input class="advlb" type="checkbox" id="${id}"${PAUSE_ATTR}><label class="advcell advthumb" for="${id}">${inner}</label><div class="advmodal"><label class="advbackdrop" for="${id}"></label><div class="advbox"><label class="advclose" for="${id}">&#10005;</label><video class="advvideo" controls preload="none" playsinline${arStyle} src="${webm}"></video><div class="advinfo">${name} &middot; Live</div></div></div>`;
1104
- return `<style>${galleryCss(minCol, maxW)}</style><div class="advgrid">${tile}</div>`;
1286
+ const videoArStyle = ar ? ` style="aspect-ratio:${ar};object-fit:fill"` : "";
1287
+ const imgAttrs = jsMode ? ` class="advlivethumb" data-base="${grabBase}" data-refresh="${refreshSec}"` : "";
1288
+ const inner = `<span class="advimg${fix}"${arStyle}><img${imgAttrs} src="${grab}" loading="lazy" alt=""><span class="advtag" style="top:5px;left:5px">&#9679; ${escHtml(this.wt.live)}</span><span class="advplay"></span></span><span class="advcap">${name}</span>`;
1289
+ const tile = `<input class="advlb" type="checkbox" id="${id}"${PAUSE_ATTR}><label class="advcell advthumb" for="${id}">${inner}</label><div class="advmodal"><label class="advbackdrop" for="${id}"></label><div class="advbox"><label class="advclose" for="${id}">&#10005;</label><video class="advvideo" controls preload="none" playsinline${videoArStyle} src="${webm}"></video><div class="advinfo">${name} &middot; Live</div></div></div>`;
1290
+ const script = jsMode ? advLiveRefreshScript() : "";
1291
+ return `<style>${galleryCss(minCol, maxW, compact, colors)}</style><div class="advgrid">${tile}</div>${script}`;
1105
1292
  }
1106
1293
  async updateLiveWidget(d, fid) {
1107
1294
  const wId = `${fid}.widget_live`;
@@ -1121,11 +1308,40 @@ class AgentDvr extends utils.Adapter {
1121
1308
  });
1122
1309
  this.ensuredFolders.add(wId);
1123
1310
  }
1311
+ if (!this.shouldRefreshLiveWidget(wId)) {
1312
+ return;
1313
+ }
1124
1314
  await this.setStateAsync(wId, { val: this.buildSingleCamLiveHtml(d), ack: true });
1125
1315
  }
1316
+ // Steuert, wie oft widget_live/widget_live_overview tatsaechlich neu
1317
+ // geschrieben werden. Jedes Neuschreiben ersetzt das komplette HTML und
1318
+ // setzt damit eine evtl. offene Video-Modal-Checkbox zurueck (schliesst
1319
+ // das Modal) - widgetLiveRefreshSec gibt Nutzern die Kontrolle ueber
1320
+ // diesen Zielkonflikt (0 = nur beim allerersten Mal schreiben, Modal
1321
+ // schliesst sich dadurch nie von selbst; >0 = alle N Sekunden aktualisieren,
1322
+ // Vorschaubild bleibt aktueller, ein offenes Modal kann aber dabei schliessen).
1323
+ shouldRefreshLiveWidget(wId) {
1324
+ const last = this.widgetLastWrite[wId];
1325
+ if (last === void 0) {
1326
+ this.widgetLastWrite[wId] = Date.now();
1327
+ return true;
1328
+ }
1329
+ if (this.config.widgetLiveMode === "js") {
1330
+ return false;
1331
+ }
1332
+ const intervalSec = Number(this.config.widgetLiveRefreshSec) || 0;
1333
+ if (intervalSec <= 0) {
1334
+ return false;
1335
+ }
1336
+ if (Date.now() - last >= intervalSec * 1e3) {
1337
+ this.widgetLastWrite[wId] = Date.now();
1338
+ return true;
1339
+ }
1340
+ return false;
1341
+ }
1126
1342
  // ---- event data points ----
1127
1343
  async writeEventDps(d, fid, events) {
1128
- var _a, _b, _c, _d, _e;
1344
+ var _a, _b, _c, _d, _e, _f, _g;
1129
1345
  const oid = d.oid;
1130
1346
  await this.ensureFolder(`${fid}.events`, "Events", "channel");
1131
1347
  await this.ensureFolder(`${fid}.events.last`, "Last event", "channel");
@@ -1194,6 +1410,7 @@ class AgentDvr extends utils.Adapter {
1194
1410
  }
1195
1411
  }
1196
1412
  let newCount = 0;
1413
+ const firstRun = this.lastEventFn[oid] === void 0;
1197
1414
  if (events.length) {
1198
1415
  const prev = this.lastEventFn[oid];
1199
1416
  if (prev !== void 0) {
@@ -1202,12 +1419,32 @@ class AgentDvr extends utils.Adapter {
1202
1419
  }
1203
1420
  this.lastEventFn[oid] = (_d = events[0].fn) != null ? _d : "";
1204
1421
  }
1422
+ const tags = /* @__PURE__ */ new Set();
1423
+ for (let i = 0; i < newCount && i < events.length; i++) {
1424
+ tokensOf((_e = events[i].tg) != null ? _e : "").forEach((t) => tags.add(t));
1425
+ }
1426
+ const known = this.eventTagsSeen[oid];
1427
+ const nextKnown = /* @__PURE__ */ new Map();
1428
+ let lateTags = 0;
1429
+ for (const ev of events.slice(0, 20)) {
1430
+ const fn = (_f = ev.fn) != null ? _f : "";
1431
+ const cur = new Set(tokensOf((_g = ev.tg) != null ? _g : ""));
1432
+ const before = known == null ? void 0 : known.get(fn);
1433
+ if (!firstRun && before) {
1434
+ for (const t of cur) {
1435
+ if (!before.has(t) && !tags.has(t)) {
1436
+ tags.add(t);
1437
+ lateTags++;
1438
+ }
1439
+ }
1440
+ }
1441
+ nextKnown.set(fn, cur);
1442
+ }
1443
+ this.eventTagsSeen[oid] = nextKnown;
1205
1444
  if (newCount > 0) {
1206
1445
  await this.pulse(`${fid}.events.new`);
1207
- const tags = /* @__PURE__ */ new Set();
1208
- for (let i = 0; i < newCount && i < events.length; i++) {
1209
- tokensOf((_e = events[i].tg) != null ? _e : "").forEach((t) => tags.add(t));
1210
- }
1446
+ }
1447
+ if (newCount > 0 || lateTags > 0) {
1211
1448
  for (const t of tags) {
1212
1449
  if (ignore.includes(t)) {
1213
1450
  continue;
@@ -1216,7 +1453,7 @@ class AgentDvr extends utils.Adapter {
1216
1453
  await this.ensureFlag(tid, `Detected: ${t}`);
1217
1454
  await this.pulse(tid);
1218
1455
  }
1219
- this.log.debug(`${newCount} new event(s) cam ${oid} [${[...tags].join(",")}]`);
1456
+ this.log.debug(`${newCount} new event(s), ${lateTags} late tag(s) cam ${oid} [${[...tags].join(",")}]`);
1220
1457
  }
1221
1458
  }
1222
1459
  // ---- camera events + widget ----
@@ -1454,7 +1691,9 @@ class AgentDvr extends utils.Adapter {
1454
1691
  });
1455
1692
  this.ensuredFolders.add(ovId);
1456
1693
  }
1457
- await this.setStateAsync(ovId, { val: this.buildOverviewHtml(cams), ack: true });
1694
+ if (this.shouldRefreshLiveWidget(ovId)) {
1695
+ await this.setStateAsync(ovId, { val: this.buildOverviewHtml(cams), ack: true });
1696
+ }
1458
1697
  }
1459
1698
  await this.setStateAsync("system.lastUpdate", { val: (/* @__PURE__ */ new Date()).toISOString(), ack: true });
1460
1699
  await this.setStateAsync("system.lastPoll", { val: Date.now(), ack: true });