iobroker.agent-dvr 0.6.0 → 0.8.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
@@ -323,6 +323,8 @@ class AgentDvr extends utils.Adapter {
323
323
  ptzPresetNames = /* @__PURE__ */ new Map();
324
324
  widgetSig = {};
325
325
  widgetLastWrite = {};
326
+ // last JSON written to the data states of the web components, to skip unchanged writes
327
+ jsonLastWrite = {};
326
328
  profileSig = "";
327
329
  lastCamNames = [];
328
330
  lastEventFn = {};
@@ -331,6 +333,8 @@ class AgentDvr extends utils.Adapter {
331
333
  eventTagsSeen = {};
332
334
  // last webhook alert pulse per camera — AgentDVR often calls the action twice per motion
333
335
  webhookLast = {};
336
+ webBaseUrl = void 0;
337
+ webBaseTimer = void 0;
334
338
  camAspect = {};
335
339
  devById = /* @__PURE__ */ new Map();
336
340
  eventBusy = {};
@@ -340,6 +344,7 @@ class AgentDvr extends utils.Adapter {
340
344
  this.on("stateChange", this.onStateChange.bind(this));
341
345
  this.on("message", this.onMessage.bind(this));
342
346
  this.on("unload", this.onUnload.bind(this));
347
+ this.on("objectChange", this.onObjectChange.bind(this));
343
348
  }
344
349
  // ---- lifecycle ----
345
350
  async ensureWebInstance() {
@@ -371,6 +376,9 @@ class AgentDvr extends utils.Adapter {
371
376
  }
372
377
  this.schedulePoll(pollSeconds * 1e3);
373
378
  this.subscribeStates("*");
379
+ this.subscribeForeignObjects("system.adapter.web.*");
380
+ this.subscribeForeignObjects("system.host.*");
381
+ this.refreshPhotoUrls().catch((e) => this.log.warn(`Photo URL refresh: ${e.message}`));
374
382
  this.log.info(`Agent DVR adapter ready. Polling ${this.baseUrl} every ${pollSeconds}s.`);
375
383
  }
376
384
  onUnload(callback) {
@@ -823,6 +831,23 @@ class AgentDvr extends utils.Adapter {
823
831
  if (dev) {
824
832
  const fid = this.deviceFolder(dev);
825
833
  const key = `${ot}_${oid}`;
834
+ const paramsId = `${fid}.events.webhookParams`;
835
+ if (!this.ensuredFolders.has(paramsId)) {
836
+ await this.ensurePath(paramsId);
837
+ await this.setObjectNotExistsAsync(paramsId, {
838
+ type: "state",
839
+ common: {
840
+ name: "Webhook parameters (JSON)",
841
+ type: "string",
842
+ role: "json",
843
+ read: true,
844
+ write: false
845
+ },
846
+ native: {}
847
+ });
848
+ this.ensuredFolders.add(paramsId);
849
+ }
850
+ await this.setStateAsync(paramsId, { val: JSON.stringify(q), ack: true });
826
851
  const cooldownMs = 2e4;
827
852
  if (Date.now() - ((_c = this.webhookLast[key]) != null ? _c : 0) >= cooldownMs) {
828
853
  this.webhookLast[key] = Date.now();
@@ -848,6 +873,59 @@ class AgentDvr extends utils.Adapter {
848
873
  }
849
874
  // Keeps the last 3 alert photos per camera in the file storage (<namespace>/<fid>/grab1..3.jpg,
850
875
  // grab1 = newest). ts1 is written last, so it is a safe trigger: the file is complete by then.
876
+ async ensureAlertPhotoObjects(ch) {
877
+ if (this.ensuredFolders.has(ch)) {
878
+ return;
879
+ }
880
+ await this.ensureFolder(ch, "Alert photos", "channel");
881
+ for (let i = 1; i <= 3; i++) {
882
+ await this.setObjectNotExistsAsync(`${ch}.grab${i}`, {
883
+ type: "state",
884
+ common: {
885
+ name: `Alert photo ${i} (file path)`,
886
+ type: "string",
887
+ role: "text",
888
+ read: true,
889
+ write: false
890
+ },
891
+ native: {}
892
+ });
893
+ await this.setObjectNotExistsAsync(`${ch}.uri${i}`, {
894
+ type: "state",
895
+ common: {
896
+ name: `Alert photo ${i} (iobfile URI)`,
897
+ type: "string",
898
+ role: "text",
899
+ read: true,
900
+ write: false
901
+ },
902
+ native: {}
903
+ });
904
+ await this.setObjectNotExistsAsync(`${ch}.url${i}`, {
905
+ type: "state",
906
+ common: {
907
+ name: `Alert photo ${i} (http URL)`,
908
+ type: "string",
909
+ role: "text.url",
910
+ read: true,
911
+ write: false
912
+ },
913
+ native: {}
914
+ });
915
+ await this.setObjectNotExistsAsync(`${ch}.ts${i}`, {
916
+ type: "state",
917
+ common: {
918
+ name: `Alert photo ${i} (time)`,
919
+ type: "number",
920
+ role: "value.time",
921
+ read: true,
922
+ write: false
923
+ },
924
+ native: {}
925
+ });
926
+ }
927
+ this.ensuredFolders.add(ch);
928
+ }
851
929
  async saveAlertPhoto(oid, fid) {
852
930
  var _a, _b;
853
931
  const img = await this.apiGetBuffer(`/photo.jpg?oid=${oid}`);
@@ -864,45 +942,7 @@ class AgentDvr extends utils.Adapter {
864
942
  });
865
943
  this.ensuredFolders.add(this.namespace);
866
944
  }
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
- }
945
+ await this.ensureAlertPhotoObjects(ch);
906
946
  for (let i = 2; i >= 1; i--) {
907
947
  try {
908
948
  const prev = await this.readFileAsync(this.namespace, `${fid}/grab${i}.jpg`);
@@ -911,15 +951,99 @@ class AgentDvr extends utils.Adapter {
911
951
  await this.setStateAsync(`${ch}.ts${i + 1}`, { val: (_b = ts == null ? void 0 : ts.val) != null ? _b : null, ack: true });
912
952
  await this.setStateAsync(`${ch}.grab${i + 1}`, { val: this.alertPhotoPath(fid, i + 1), ack: true });
913
953
  await this.setStateAsync(`${ch}.uri${i + 1}`, { val: this.alertPhotoUri(fid, i + 1), ack: true });
954
+ await this.setStateAsync(`${ch}.url${i + 1}`, { val: await this.alertPhotoUrl(fid, i + 1), ack: true });
914
955
  } catch {
915
956
  }
916
957
  }
917
958
  await this.writeFileAsync(this.namespace, `${fid}/grab1.jpg`, img.data);
918
959
  await this.setStateAsync(`${ch}.grab1`, { val: this.alertPhotoPath(fid, 1), ack: true });
919
960
  await this.setStateAsync(`${ch}.uri1`, { val: this.alertPhotoUri(fid, 1), ack: true });
961
+ await this.setStateAsync(`${ch}.url1`, { val: await this.alertPhotoUrl(fid, 1), ack: true });
920
962
  await this.setStateAsync(`${ch}.ts1`, { val: Date.now(), ack: true });
921
963
  this.log.debug(`Alert photo cam ${oid} saved (${img.data.length} bytes)`);
922
964
  }
965
+ onObjectChange(id) {
966
+ if (!/^system\.adapter\.web\.\d+$/.test(id) && !id.startsWith("system.host.")) {
967
+ return;
968
+ }
969
+ if (this.webBaseTimer !== void 0) {
970
+ this.clearTimeout(this.webBaseTimer);
971
+ }
972
+ this.webBaseTimer = this.setTimeout(() => {
973
+ this.webBaseTimer = void 0;
974
+ this.refreshPhotoUrls().catch((e) => this.log.warn(`Photo URL refresh: ${e.message}`));
975
+ }, 2e3);
976
+ }
977
+ // Recomputes the web base URL and rewrites url1..3 of every camera that already has alert photos.
978
+ async refreshPhotoUrls() {
979
+ const base = await this.findWebBaseUrl();
980
+ if (base === this.webBaseUrl) {
981
+ return;
982
+ }
983
+ this.log.info(`Alert photo links now use ${base || "(no web instance)"}`);
984
+ this.webBaseUrl = base;
985
+ for (const dev of this.devById.values()) {
986
+ const fid = this.deviceFolder(dev);
987
+ if (!await this.getObjectAsync(`${fid}.alertPhotos`)) {
988
+ continue;
989
+ }
990
+ await this.ensureAlertPhotoObjects(`${fid}.alertPhotos`);
991
+ for (let n = 1; n <= 3; n++) {
992
+ await this.setStateAsync(`${fid}.alertPhotos.url${n}`, {
993
+ val: await this.alertPhotoUrl(fid, n),
994
+ ack: true
995
+ });
996
+ }
997
+ }
998
+ }
999
+ // http(s) URL of a stored alert photo via the web extension, for apps that only accept web links
1000
+ async alertPhotoUrl(fid, n) {
1001
+ if (this.webBaseUrl === void 0) {
1002
+ this.webBaseUrl = await this.findWebBaseUrl();
1003
+ }
1004
+ return this.webBaseUrl ? `${this.webBaseUrl}/${this.namespace}/photos/${fid}/grab${n}.jpg` : "";
1005
+ }
1006
+ // Base URL of the web instance that serves this adapter's extension — prefers plain http,
1007
+ // since TV and kiosk apps often reject self-signed certificates.
1008
+ async findWebBaseUrl() {
1009
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1010
+ try {
1011
+ const view = await this.getObjectViewAsync("system", "instance", {
1012
+ startkey: "system.adapter.web.",
1013
+ endkey: "system.adapter.web.\u9999"
1014
+ });
1015
+ const own = await this.getForeignObjectAsync(`system.adapter.${this.namespace}`);
1016
+ const loadedBy = String((_b = (_a = own == null ? void 0 : own.native) == null ? void 0 : _a.webInstance) != null ? _b : "*");
1017
+ const chosen = this.config.photoWebInstance || "";
1018
+ const webs = view.rows.map((r) => r.value).filter((o) => {
1019
+ var _a2;
1020
+ return ((_a2 = o == null ? void 0 : o.common) == null ? void 0 : _a2.enabled) && (loadedBy === "*" || o._id === `system.adapter.${loadedBy}`);
1021
+ }).filter((o) => !chosen || o._id === `system.adapter.${chosen}`).sort((a, b) => {
1022
+ var _a2, _b2;
1023
+ return Number(!!((_a2 = a.native) == null ? void 0 : _a2.secure)) - Number(!!((_b2 = b.native) == null ? void 0 : _b2.secure));
1024
+ });
1025
+ const web = webs[0];
1026
+ if (!web) {
1027
+ return "";
1028
+ }
1029
+ let host = String((_d = (_c = web.native) == null ? void 0 : _c.bind) != null ? _d : "");
1030
+ if (!host || host === "0.0.0.0" || host === "::") {
1031
+ const hostObj = await this.getForeignObjectAsync(`system.host.${web.common.host}`);
1032
+ const addrs = ((_f = (_e = hostObj == null ? void 0 : hostObj.common) == null ? void 0 : _e.address) != null ? _f : []).filter(
1033
+ (a) => /^\d+\.\d+\.\d+\.\d+$/.test(a) && !a.startsWith("127.")
1034
+ );
1035
+ host = (_g = addrs[0]) != null ? _g : "";
1036
+ }
1037
+ if (!host) {
1038
+ return "";
1039
+ }
1040
+ const proto = ((_h = web.native) == null ? void 0 : _h.secure) ? "https" : "http";
1041
+ return `${proto}://${host}:${(_j = (_i = web.native) == null ? void 0 : _i.port) != null ? _j : 8082}`;
1042
+ } catch (e) {
1043
+ this.log.debug(`Web base URL not found: ${e.message}`);
1044
+ return "";
1045
+ }
1046
+ }
923
1047
  // ioBroker file URI of a stored alert photo — resolved by telegram >= 6 directly from the file storage
924
1048
  alertPhotoUri(fid, n) {
925
1049
  return `iobfile://${this.namespace}/${fid}/grab${n}.jpg`;
@@ -1168,6 +1292,69 @@ class AgentDvr extends utils.Adapter {
1168
1292
  }
1169
1293
  }
1170
1294
  }
1295
+ // ---- web components (admin/webcomponents) ----
1296
+ // Die Widget-Einstellungen der Instanz, so wie sie die HTML-Widgets anwenden - die
1297
+ // Web-Komponenten lesen sie aus widget_config (Modus "aus den Adapter-Einstellungen").
1298
+ // Die Schluessel heissen wie die Einstellungen im Manifest der Komponenten.
1299
+ widgetComponentSettings() {
1300
+ var _a;
1301
+ const c = this.config;
1302
+ return {
1303
+ widgetMode: c.widgetMode === "js" ? "js" : "nojs",
1304
+ count: Math.max(1, Number(c.widgetAnzahl) || 50),
1305
+ minCol: this.effectiveMinCol(),
1306
+ maxModalWidth: c.widgetMaxModalWidth || 900,
1307
+ showTags: !!c.widgetShowTags,
1308
+ tagPosition: c.widgetTagPosition || "bottom-left",
1309
+ sortNewest: c.widgetSortNewest !== false,
1310
+ showSearch: c.widgetShowSearch !== false,
1311
+ defaultTag: (c.widgetDefaultTag || "").trim(),
1312
+ compact: !!c.widgetCompact,
1313
+ playerUrl: (c.widgetPlayerUrl || "").trim(),
1314
+ liveAspect: c.widgetLiveAspect || "",
1315
+ liveRefreshSec: Math.max(0, Number(c.widgetLiveRefreshSec) || 0),
1316
+ colorCardBg: c.widgetColorCardBg || "",
1317
+ colorTagBg: c.widgetColorTagBg || "",
1318
+ colorTagText: c.widgetColorTagText || "",
1319
+ colorAccent: c.widgetColorAccent || "",
1320
+ colorModalBg: c.widgetColorModalBg || "",
1321
+ borderRadius: (_a = c.widgetBorderRadius) != null ? _a : 8
1322
+ };
1323
+ }
1324
+ // Writes a JSON data state for the web components - only when its content changed.
1325
+ async writeJsonState(id, name, data) {
1326
+ const val = JSON.stringify(data);
1327
+ if (!this.ensuredFolders.has(id)) {
1328
+ await this.setObjectNotExistsAsync(id, {
1329
+ type: "state",
1330
+ common: { name, type: "string", role: "json", read: true, write: false, def: "" },
1331
+ native: {}
1332
+ });
1333
+ this.ensuredFolders.add(id);
1334
+ delete this.jsonLastWrite[id];
1335
+ }
1336
+ if (this.jsonLastWrite[id] === val) {
1337
+ return;
1338
+ }
1339
+ await this.setStateAsync(id, { val, ack: true });
1340
+ this.jsonLastWrite[id] = val;
1341
+ }
1342
+ // widget_config: settings, cameras and labels for the web components. No credentials:
1343
+ // the links are the same AgentDVR links the HTML widgets put into the page.
1344
+ async writeWidgetConfig(cams) {
1345
+ await this.writeJsonState("widget_config", "Widget settings and cameras (for the web components)", {
1346
+ settings: this.widgetComponentSettings(),
1347
+ labels: this.wt,
1348
+ cameras: cams.map((d) => ({
1349
+ id: this.deviceFolder(d),
1350
+ oid: d.oid,
1351
+ name: d.name || `Camera ${d.oid}`,
1352
+ aspect: this.camAspect[d.oid] || "",
1353
+ snapshot: `${this.baseUrl}/grab.jpg?oid=${d.oid}&ot=2&maintainAR=1`,
1354
+ live: `${this.baseUrl}/video.webm?oid=${d.oid}&ot=2`
1355
+ }))
1356
+ });
1357
+ }
1171
1358
  sortedEvents(events) {
1172
1359
  return this.config.widgetSortNewest === false ? [...events].reverse() : events;
1173
1360
  }
@@ -1479,6 +1666,22 @@ class AgentDvr extends utils.Adapter {
1479
1666
  if (this.config.enableEventDps) {
1480
1667
  await this.writeEventDps(d, fid, events);
1481
1668
  }
1669
+ await this.writeJsonState(`${fid}.widget_data`, "Recordings (for the web components)", {
1670
+ recordings: events.slice(0, 500).map((ev) => {
1671
+ const p = this.fmtEvent(ev, d.oid);
1672
+ return {
1673
+ fn: p.fn,
1674
+ date: p.date,
1675
+ time: p.time,
1676
+ dur: p.dur,
1677
+ size: p.sizeMB,
1678
+ tag: p.tag,
1679
+ thumb: p.thumb,
1680
+ video: p.video,
1681
+ ts: p.ts
1682
+ };
1683
+ })
1684
+ });
1482
1685
  if (this.config.enableWidget) {
1483
1686
  const wId = `${fid}.widget_recordings`;
1484
1687
  if (!this.ensuredFolders.has(wId)) {
@@ -1673,6 +1876,7 @@ class AgentDvr extends utils.Adapter {
1673
1876
  }
1674
1877
  }
1675
1878
  }
1879
+ await this.writeWidgetConfig(devices.filter((d) => d.ot === 2));
1676
1880
  if (this.config.enableOverview) {
1677
1881
  const cams = devices.filter((d) => d.ot === 2);
1678
1882
  const ovId = "widget_live_overview";