iobroker.agent-dvr 0.5.5 → 0.7.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" },
@@ -325,6 +326,13 @@ class AgentDvr extends utils.Adapter {
325
326
  profileSig = "";
326
327
  lastCamNames = [];
327
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 = {};
334
+ webBaseUrl = void 0;
335
+ webBaseTimer = void 0;
328
336
  camAspect = {};
329
337
  devById = /* @__PURE__ */ new Map();
330
338
  eventBusy = {};
@@ -334,6 +342,7 @@ class AgentDvr extends utils.Adapter {
334
342
  this.on("stateChange", this.onStateChange.bind(this));
335
343
  this.on("message", this.onMessage.bind(this));
336
344
  this.on("unload", this.onUnload.bind(this));
345
+ this.on("objectChange", this.onObjectChange.bind(this));
337
346
  }
338
347
  // ---- lifecycle ----
339
348
  async ensureWebInstance() {
@@ -365,6 +374,9 @@ class AgentDvr extends utils.Adapter {
365
374
  }
366
375
  this.schedulePoll(pollSeconds * 1e3);
367
376
  this.subscribeStates("*");
377
+ this.subscribeForeignObjects("system.adapter.web.*");
378
+ this.subscribeForeignObjects("system.host.*");
379
+ this.refreshPhotoUrls().catch((e) => this.log.warn(`Photo URL refresh: ${e.message}`));
368
380
  this.log.info(`Agent DVR adapter ready. Polling ${this.baseUrl} every ${pollSeconds}s.`);
369
381
  }
370
382
  onUnload(callback) {
@@ -473,6 +485,10 @@ class AgentDvr extends utils.Adapter {
473
485
  return;
474
486
  }
475
487
  const relId = this.getRelId(id);
488
+ if (relId === "system.webhook") {
489
+ this.onWebhook(state.val).catch((e) => this.log.warn(`Webhook error: ${e.message}`));
490
+ return;
491
+ }
476
492
  const entry = this.registry.get(relId);
477
493
  if (entry) {
478
494
  this.runCommand(relId, entry, state.val).catch(
@@ -484,7 +500,7 @@ class AgentDvr extends utils.Adapter {
484
500
  getRelId(fullId) {
485
501
  return fullId.startsWith(`${this.namespace}.`) ? fullId.slice(this.namespace.length + 1) : fullId;
486
502
  }
487
- apiGet(path) {
503
+ apiGet(path2) {
488
504
  return new Promise((resolve) => {
489
505
  var _a;
490
506
  const rawTimeout = (_a = this.config.httpTimeoutMs) != null ? _a : 8e3;
@@ -495,7 +511,7 @@ class AgentDvr extends utils.Adapter {
495
511
  const opts = {
496
512
  hostname: this.config.serverIp,
497
513
  port: this.config.port || 8090,
498
- path,
514
+ path: path2,
499
515
  method: "GET",
500
516
  timeout
501
517
  };
@@ -528,7 +544,7 @@ class AgentDvr extends utils.Adapter {
528
544
  }
529
545
  });
530
546
  }
531
- apiGetBuffer(path) {
547
+ apiGetBuffer(path2) {
532
548
  return new Promise((resolve) => {
533
549
  var _a;
534
550
  const rawTimeout = (_a = this.config.httpTimeoutMs) != null ? _a : 8e3;
@@ -539,7 +555,7 @@ class AgentDvr extends utils.Adapter {
539
555
  const opts = {
540
556
  hostname: this.config.serverIp,
541
557
  port: this.config.port || 8090,
542
- path,
558
+ path: path2,
543
559
  method: "GET",
544
560
  timeout
545
561
  };
@@ -734,6 +750,20 @@ class AgentDvr extends utils.Adapter {
734
750
  await this.writeLeaf("system.lastUpdate", "");
735
751
  await this.writeLeaf("system.lastPoll", 0);
736
752
  await this.writeLeaf("system.cameraCount", 0);
753
+ if (!this.ensuredFolders.has("system.webhook")) {
754
+ await this.setObjectNotExistsAsync("system.webhook", {
755
+ type: "state",
756
+ common: {
757
+ name: "Last webhook call (JSON)",
758
+ type: "string",
759
+ role: "json",
760
+ read: true,
761
+ write: true
762
+ },
763
+ native: {}
764
+ });
765
+ this.ensuredFolders.add("system.webhook");
766
+ }
737
767
  if (this.config.enableSystemControls) {
738
768
  await this.ensureFolder("system.control", "Control", "channel");
739
769
  for (const c of SYS_COMMANDS) {
@@ -781,6 +811,246 @@ class AgentDvr extends utils.Adapter {
781
811
  this.log.debug(`cam ${d.oid} resolution ${wh[0]}x${wh[1]} -> AR ${this.camAspect[d.oid]}`);
782
812
  }
783
813
  }
814
+ // ---- webhook ----
815
+ // Written by the web extension (lib/web.js) when AgentDVR calls the webhook with ?oid={ID}.
816
+ // Pulses <cam>.events.webhook right away — before the poll — so scripts can grab a photo
817
+ // at the moment of the alert, then refreshes all data.
818
+ async onWebhook(val) {
819
+ var _a, _b, _c;
820
+ let q = {};
821
+ try {
822
+ q = JSON.parse(String(val != null ? val : "{}"));
823
+ } catch {
824
+ }
825
+ await this.setStateAsync("system.webhook", { val: String(val != null ? val : ""), ack: true });
826
+ const oid = `${(_a = q.oid) != null ? _a : ""}`;
827
+ const ot = `${(_b = q.ot) != null ? _b : "2"}`;
828
+ const dev = [...this.devById.values()].find((d) => String(d.oid) === oid && String(d.ot) === ot);
829
+ if (dev) {
830
+ const fid = this.deviceFolder(dev);
831
+ const key = `${ot}_${oid}`;
832
+ const paramsId = `${fid}.events.webhookParams`;
833
+ if (!this.ensuredFolders.has(paramsId)) {
834
+ await this.ensurePath(paramsId);
835
+ await this.setObjectNotExistsAsync(paramsId, {
836
+ type: "state",
837
+ common: {
838
+ name: "Webhook parameters (JSON)",
839
+ type: "string",
840
+ role: "json",
841
+ read: true,
842
+ write: false
843
+ },
844
+ native: {}
845
+ });
846
+ this.ensuredFolders.add(paramsId);
847
+ }
848
+ await this.setStateAsync(paramsId, { val: JSON.stringify(q), ack: true });
849
+ const cooldownMs = 2e4;
850
+ if (Date.now() - ((_c = this.webhookLast[key]) != null ? _c : 0) >= cooldownMs) {
851
+ this.webhookLast[key] = Date.now();
852
+ await this.ensureFlag(`${fid}.events.webhook`, "Webhook alert (AgentDVR action)");
853
+ await this.pulse(`${fid}.events.webhook`);
854
+ this.log.debug(`Webhook alert cam ${oid} \u2192 ${fid}.events.webhook`);
855
+ if (this.config.enableAlertPhotos !== false && dev.ot === 2) {
856
+ this.saveAlertPhoto(dev.oid, fid).catch(
857
+ (e) => this.log.warn(`Alert photo cam ${oid}: ${e.message}`)
858
+ );
859
+ }
860
+ } else {
861
+ this.log.debug(`Webhook alert cam ${oid} ignored (cooldown)`);
862
+ }
863
+ } else if (oid) {
864
+ this.log.debug(`Webhook: no device with oid ${oid} / ot ${ot}`);
865
+ }
866
+ if (this.pollBusy) {
867
+ this.scheduleRefresh();
868
+ } else {
869
+ await this.poll().catch((e) => this.log.warn(`Webhook refresh error: ${e.message}`));
870
+ }
871
+ }
872
+ // Keeps the last 3 alert photos per camera in the file storage (<namespace>/<fid>/grab1..3.jpg,
873
+ // grab1 = newest). ts1 is written last, so it is a safe trigger: the file is complete by then.
874
+ async ensureAlertPhotoObjects(ch) {
875
+ if (this.ensuredFolders.has(ch)) {
876
+ return;
877
+ }
878
+ await this.ensureFolder(ch, "Alert photos", "channel");
879
+ for (let i = 1; i <= 3; i++) {
880
+ await this.setObjectNotExistsAsync(`${ch}.grab${i}`, {
881
+ type: "state",
882
+ common: {
883
+ name: `Alert photo ${i} (file path)`,
884
+ type: "string",
885
+ role: "text",
886
+ read: true,
887
+ write: false
888
+ },
889
+ native: {}
890
+ });
891
+ await this.setObjectNotExistsAsync(`${ch}.uri${i}`, {
892
+ type: "state",
893
+ common: {
894
+ name: `Alert photo ${i} (iobfile URI)`,
895
+ type: "string",
896
+ role: "text",
897
+ read: true,
898
+ write: false
899
+ },
900
+ native: {}
901
+ });
902
+ await this.setObjectNotExistsAsync(`${ch}.url${i}`, {
903
+ type: "state",
904
+ common: {
905
+ name: `Alert photo ${i} (http URL)`,
906
+ type: "string",
907
+ role: "text.url",
908
+ read: true,
909
+ write: false
910
+ },
911
+ native: {}
912
+ });
913
+ await this.setObjectNotExistsAsync(`${ch}.ts${i}`, {
914
+ type: "state",
915
+ common: {
916
+ name: `Alert photo ${i} (time)`,
917
+ type: "number",
918
+ role: "value.time",
919
+ read: true,
920
+ write: false
921
+ },
922
+ native: {}
923
+ });
924
+ }
925
+ this.ensuredFolders.add(ch);
926
+ }
927
+ async saveAlertPhoto(oid, fid) {
928
+ var _a, _b;
929
+ const img = await this.apiGetBuffer(`/photo.jpg?oid=${oid}`);
930
+ if (!img.ok || !img.data) {
931
+ this.log.warn(`Alert photo cam ${oid} not fetched: ${(_a = img.error) != null ? _a : "empty response"}`);
932
+ return;
933
+ }
934
+ const ch = `${fid}.alertPhotos`;
935
+ if (!this.ensuredFolders.has(this.namespace)) {
936
+ await this.setForeignObjectNotExistsAsync(this.namespace, {
937
+ type: "meta",
938
+ common: { name: "Alert photos", type: "meta.user" },
939
+ native: {}
940
+ });
941
+ this.ensuredFolders.add(this.namespace);
942
+ }
943
+ await this.ensureAlertPhotoObjects(ch);
944
+ for (let i = 2; i >= 1; i--) {
945
+ try {
946
+ const prev = await this.readFileAsync(this.namespace, `${fid}/grab${i}.jpg`);
947
+ await this.writeFileAsync(this.namespace, `${fid}/grab${i + 1}.jpg`, prev.file);
948
+ const ts = await this.getStateAsync(`${ch}.ts${i}`);
949
+ await this.setStateAsync(`${ch}.ts${i + 1}`, { val: (_b = ts == null ? void 0 : ts.val) != null ? _b : null, ack: true });
950
+ await this.setStateAsync(`${ch}.grab${i + 1}`, { val: this.alertPhotoPath(fid, i + 1), ack: true });
951
+ await this.setStateAsync(`${ch}.uri${i + 1}`, { val: this.alertPhotoUri(fid, i + 1), ack: true });
952
+ await this.setStateAsync(`${ch}.url${i + 1}`, { val: await this.alertPhotoUrl(fid, i + 1), ack: true });
953
+ } catch {
954
+ }
955
+ }
956
+ await this.writeFileAsync(this.namespace, `${fid}/grab1.jpg`, img.data);
957
+ await this.setStateAsync(`${ch}.grab1`, { val: this.alertPhotoPath(fid, 1), ack: true });
958
+ await this.setStateAsync(`${ch}.uri1`, { val: this.alertPhotoUri(fid, 1), ack: true });
959
+ await this.setStateAsync(`${ch}.url1`, { val: await this.alertPhotoUrl(fid, 1), ack: true });
960
+ await this.setStateAsync(`${ch}.ts1`, { val: Date.now(), ack: true });
961
+ this.log.debug(`Alert photo cam ${oid} saved (${img.data.length} bytes)`);
962
+ }
963
+ onObjectChange(id) {
964
+ if (!/^system\.adapter\.web\.\d+$/.test(id) && !id.startsWith("system.host.")) {
965
+ return;
966
+ }
967
+ if (this.webBaseTimer !== void 0) {
968
+ this.clearTimeout(this.webBaseTimer);
969
+ }
970
+ this.webBaseTimer = this.setTimeout(() => {
971
+ this.webBaseTimer = void 0;
972
+ this.refreshPhotoUrls().catch((e) => this.log.warn(`Photo URL refresh: ${e.message}`));
973
+ }, 2e3);
974
+ }
975
+ // Recomputes the web base URL and rewrites url1..3 of every camera that already has alert photos.
976
+ async refreshPhotoUrls() {
977
+ const base = await this.findWebBaseUrl();
978
+ if (base === this.webBaseUrl) {
979
+ return;
980
+ }
981
+ this.log.info(`Alert photo links now use ${base || "(no web instance)"}`);
982
+ this.webBaseUrl = base;
983
+ for (const dev of this.devById.values()) {
984
+ const fid = this.deviceFolder(dev);
985
+ if (!await this.getObjectAsync(`${fid}.alertPhotos`)) {
986
+ continue;
987
+ }
988
+ await this.ensureAlertPhotoObjects(`${fid}.alertPhotos`);
989
+ for (let n = 1; n <= 3; n++) {
990
+ await this.setStateAsync(`${fid}.alertPhotos.url${n}`, {
991
+ val: await this.alertPhotoUrl(fid, n),
992
+ ack: true
993
+ });
994
+ }
995
+ }
996
+ }
997
+ // http(s) URL of a stored alert photo via the web extension, for apps that only accept web links
998
+ async alertPhotoUrl(fid, n) {
999
+ if (this.webBaseUrl === void 0) {
1000
+ this.webBaseUrl = await this.findWebBaseUrl();
1001
+ }
1002
+ return this.webBaseUrl ? `${this.webBaseUrl}/${this.namespace}/photos/${fid}/grab${n}.jpg` : "";
1003
+ }
1004
+ // Base URL of the web instance that serves this adapter's extension — prefers plain http,
1005
+ // since TV and kiosk apps often reject self-signed certificates.
1006
+ async findWebBaseUrl() {
1007
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1008
+ try {
1009
+ const view = await this.getObjectViewAsync("system", "instance", {
1010
+ startkey: "system.adapter.web.",
1011
+ endkey: "system.adapter.web.\u9999"
1012
+ });
1013
+ const own = await this.getForeignObjectAsync(`system.adapter.${this.namespace}`);
1014
+ const loadedBy = String((_b = (_a = own == null ? void 0 : own.native) == null ? void 0 : _a.webInstance) != null ? _b : "*");
1015
+ const chosen = this.config.photoWebInstance || "";
1016
+ const webs = view.rows.map((r) => r.value).filter((o) => {
1017
+ var _a2;
1018
+ return ((_a2 = o == null ? void 0 : o.common) == null ? void 0 : _a2.enabled) && (loadedBy === "*" || o._id === `system.adapter.${loadedBy}`);
1019
+ }).filter((o) => !chosen || o._id === `system.adapter.${chosen}`).sort((a, b) => {
1020
+ var _a2, _b2;
1021
+ return Number(!!((_a2 = a.native) == null ? void 0 : _a2.secure)) - Number(!!((_b2 = b.native) == null ? void 0 : _b2.secure));
1022
+ });
1023
+ const web = webs[0];
1024
+ if (!web) {
1025
+ return "";
1026
+ }
1027
+ let host = String((_d = (_c = web.native) == null ? void 0 : _c.bind) != null ? _d : "");
1028
+ if (!host || host === "0.0.0.0" || host === "::") {
1029
+ const hostObj = await this.getForeignObjectAsync(`system.host.${web.common.host}`);
1030
+ const addrs = ((_f = (_e = hostObj == null ? void 0 : hostObj.common) == null ? void 0 : _e.address) != null ? _f : []).filter(
1031
+ (a) => /^\d+\.\d+\.\d+\.\d+$/.test(a) && !a.startsWith("127.")
1032
+ );
1033
+ host = (_g = addrs[0]) != null ? _g : "";
1034
+ }
1035
+ if (!host) {
1036
+ return "";
1037
+ }
1038
+ const proto = ((_h = web.native) == null ? void 0 : _h.secure) ? "https" : "http";
1039
+ return `${proto}://${host}:${(_j = (_i = web.native) == null ? void 0 : _i.port) != null ? _j : 8082}`;
1040
+ } catch (e) {
1041
+ this.log.debug(`Web base URL not found: ${e.message}`);
1042
+ return "";
1043
+ }
1044
+ }
1045
+ // ioBroker file URI of a stored alert photo — resolved by telegram >= 6 directly from the file storage
1046
+ alertPhotoUri(fid, n) {
1047
+ return `iobfile://${this.namespace}/${fid}/grab${n}.jpg`;
1048
+ }
1049
+ // Absolute path of a stored alert photo, for consumers that need a local file (e.g. telegram).
1050
+ // Only valid when the file storage lives on this host's disk (default jsonl/file DB).
1051
+ alertPhotoPath(fid, n) {
1052
+ return path.join(utils.getAbsoluteDefaultDataDir(), "files", this.namespace, fid, `grab${n}.jpg`);
1053
+ }
784
1054
  // ---- device folder name ----
785
1055
  deviceFolder(d) {
786
1056
  return `${d.ot === 1 ? "mic" : "cam"}_${sanitize(d.oid)}_${sanitize(d.name)}`;
@@ -1193,7 +1463,7 @@ class AgentDvr extends utils.Adapter {
1193
1463
  }
1194
1464
  // ---- event data points ----
1195
1465
  async writeEventDps(d, fid, events) {
1196
- var _a, _b, _c, _d, _e;
1466
+ var _a, _b, _c, _d, _e, _f, _g;
1197
1467
  const oid = d.oid;
1198
1468
  await this.ensureFolder(`${fid}.events`, "Events", "channel");
1199
1469
  await this.ensureFolder(`${fid}.events.last`, "Last event", "channel");
@@ -1262,6 +1532,7 @@ class AgentDvr extends utils.Adapter {
1262
1532
  }
1263
1533
  }
1264
1534
  let newCount = 0;
1535
+ const firstRun = this.lastEventFn[oid] === void 0;
1265
1536
  if (events.length) {
1266
1537
  const prev = this.lastEventFn[oid];
1267
1538
  if (prev !== void 0) {
@@ -1270,12 +1541,32 @@ class AgentDvr extends utils.Adapter {
1270
1541
  }
1271
1542
  this.lastEventFn[oid] = (_d = events[0].fn) != null ? _d : "";
1272
1543
  }
1544
+ const tags = /* @__PURE__ */ new Set();
1545
+ for (let i = 0; i < newCount && i < events.length; i++) {
1546
+ tokensOf((_e = events[i].tg) != null ? _e : "").forEach((t) => tags.add(t));
1547
+ }
1548
+ const known = this.eventTagsSeen[oid];
1549
+ const nextKnown = /* @__PURE__ */ new Map();
1550
+ let lateTags = 0;
1551
+ for (const ev of events.slice(0, 20)) {
1552
+ const fn = (_f = ev.fn) != null ? _f : "";
1553
+ const cur = new Set(tokensOf((_g = ev.tg) != null ? _g : ""));
1554
+ const before = known == null ? void 0 : known.get(fn);
1555
+ if (!firstRun && before) {
1556
+ for (const t of cur) {
1557
+ if (!before.has(t) && !tags.has(t)) {
1558
+ tags.add(t);
1559
+ lateTags++;
1560
+ }
1561
+ }
1562
+ }
1563
+ nextKnown.set(fn, cur);
1564
+ }
1565
+ this.eventTagsSeen[oid] = nextKnown;
1273
1566
  if (newCount > 0) {
1274
1567
  await this.pulse(`${fid}.events.new`);
1275
- const tags = /* @__PURE__ */ new Set();
1276
- for (let i = 0; i < newCount && i < events.length; i++) {
1277
- tokensOf((_e = events[i].tg) != null ? _e : "").forEach((t) => tags.add(t));
1278
- }
1568
+ }
1569
+ if (newCount > 0 || lateTags > 0) {
1279
1570
  for (const t of tags) {
1280
1571
  if (ignore.includes(t)) {
1281
1572
  continue;
@@ -1284,7 +1575,7 @@ class AgentDvr extends utils.Adapter {
1284
1575
  await this.ensureFlag(tid, `Detected: ${t}`);
1285
1576
  await this.pulse(tid);
1286
1577
  }
1287
- this.log.debug(`${newCount} new event(s) cam ${oid} [${[...tags].join(",")}]`);
1578
+ this.log.debug(`${newCount} new event(s), ${lateTags} late tag(s) cam ${oid} [${[...tags].join(",")}]`);
1288
1579
  }
1289
1580
  }
1290
1581
  // ---- camera events + widget ----