iobroker.agent-dvr 0.5.5 → 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" },
@@ -325,6 +326,11 @@ 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 = {};
328
334
  camAspect = {};
329
335
  devById = /* @__PURE__ */ new Map();
330
336
  eventBusy = {};
@@ -473,6 +479,10 @@ class AgentDvr extends utils.Adapter {
473
479
  return;
474
480
  }
475
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
+ }
476
486
  const entry = this.registry.get(relId);
477
487
  if (entry) {
478
488
  this.runCommand(relId, entry, state.val).catch(
@@ -484,7 +494,7 @@ class AgentDvr extends utils.Adapter {
484
494
  getRelId(fullId) {
485
495
  return fullId.startsWith(`${this.namespace}.`) ? fullId.slice(this.namespace.length + 1) : fullId;
486
496
  }
487
- apiGet(path) {
497
+ apiGet(path2) {
488
498
  return new Promise((resolve) => {
489
499
  var _a;
490
500
  const rawTimeout = (_a = this.config.httpTimeoutMs) != null ? _a : 8e3;
@@ -495,7 +505,7 @@ class AgentDvr extends utils.Adapter {
495
505
  const opts = {
496
506
  hostname: this.config.serverIp,
497
507
  port: this.config.port || 8090,
498
- path,
508
+ path: path2,
499
509
  method: "GET",
500
510
  timeout
501
511
  };
@@ -528,7 +538,7 @@ class AgentDvr extends utils.Adapter {
528
538
  }
529
539
  });
530
540
  }
531
- apiGetBuffer(path) {
541
+ apiGetBuffer(path2) {
532
542
  return new Promise((resolve) => {
533
543
  var _a;
534
544
  const rawTimeout = (_a = this.config.httpTimeoutMs) != null ? _a : 8e3;
@@ -539,7 +549,7 @@ class AgentDvr extends utils.Adapter {
539
549
  const opts = {
540
550
  hostname: this.config.serverIp,
541
551
  port: this.config.port || 8090,
542
- path,
552
+ path: path2,
543
553
  method: "GET",
544
554
  timeout
545
555
  };
@@ -734,6 +744,20 @@ class AgentDvr extends utils.Adapter {
734
744
  await this.writeLeaf("system.lastUpdate", "");
735
745
  await this.writeLeaf("system.lastPoll", 0);
736
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
+ }
737
761
  if (this.config.enableSystemControls) {
738
762
  await this.ensureFolder("system.control", "Control", "channel");
739
763
  for (const c of SYS_COMMANDS) {
@@ -781,6 +805,130 @@ class AgentDvr extends utils.Adapter {
781
805
  this.log.debug(`cam ${d.oid} resolution ${wh[0]}x${wh[1]} -> AR ${this.camAspect[d.oid]}`);
782
806
  }
783
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
+ }
784
932
  // ---- device folder name ----
785
933
  deviceFolder(d) {
786
934
  return `${d.ot === 1 ? "mic" : "cam"}_${sanitize(d.oid)}_${sanitize(d.name)}`;
@@ -1193,7 +1341,7 @@ class AgentDvr extends utils.Adapter {
1193
1341
  }
1194
1342
  // ---- event data points ----
1195
1343
  async writeEventDps(d, fid, events) {
1196
- var _a, _b, _c, _d, _e;
1344
+ var _a, _b, _c, _d, _e, _f, _g;
1197
1345
  const oid = d.oid;
1198
1346
  await this.ensureFolder(`${fid}.events`, "Events", "channel");
1199
1347
  await this.ensureFolder(`${fid}.events.last`, "Last event", "channel");
@@ -1262,6 +1410,7 @@ class AgentDvr extends utils.Adapter {
1262
1410
  }
1263
1411
  }
1264
1412
  let newCount = 0;
1413
+ const firstRun = this.lastEventFn[oid] === void 0;
1265
1414
  if (events.length) {
1266
1415
  const prev = this.lastEventFn[oid];
1267
1416
  if (prev !== void 0) {
@@ -1270,12 +1419,32 @@ class AgentDvr extends utils.Adapter {
1270
1419
  }
1271
1420
  this.lastEventFn[oid] = (_d = events[0].fn) != null ? _d : "";
1272
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;
1273
1444
  if (newCount > 0) {
1274
1445
  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
- }
1446
+ }
1447
+ if (newCount > 0 || lateTags > 0) {
1279
1448
  for (const t of tags) {
1280
1449
  if (ignore.includes(t)) {
1281
1450
  continue;
@@ -1284,7 +1453,7 @@ class AgentDvr extends utils.Adapter {
1284
1453
  await this.ensureFlag(tid, `Detected: ${t}`);
1285
1454
  await this.pulse(tid);
1286
1455
  }
1287
- 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(",")}]`);
1288
1457
  }
1289
1458
  }
1290
1459
  // ---- camera events + widget ----