@pmndre/pine 0.22.1 → 0.33.1
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/README.md +2 -1
- package/changes.json +264 -0
- package/docs/SKILL.md +31 -7
- package/docs/references/agents.md +245 -21
- package/docs/references/coding.md +1 -1
- package/docs/references/computer.md +1 -1
- package/docs/references/configuration.md +14 -5
- package/docs/references/mcp.md +9 -0
- package/docs/references/operations.md +21 -10
- package/docs/references/overview.md +3 -1
- package/docs/references/security.md +83 -24
- package/docs/references/setup.md +55 -9
- package/docs/references/source-types.md +1418 -0
- package/docs/references/sources.md +333 -19
- package/docs/references/stack.md +1 -0
- package/docs/references/tui.md +86 -12
- package/examples/home/AGENTS.md +4 -0
- package/examples/home/TOOLS.md +5 -0
- package/examples/home/agents/main/workspace/AGENTS.md +1 -1
- package/examples/home/agents/main/workspace/TOOLS.md +5 -0
- package/mcp/browser.d.ts +6 -0
- package/mcp/browser.js +19 -0
- package/mcp/render.d.ts +1 -0
- package/mcp/render.js +237 -0
- package/package.json +6 -4
- package/src/actions.d.ts +6 -1
- package/src/actions.js +17 -4
- package/src/admin.d.ts +4 -0
- package/src/admin.js +25 -6
- package/src/agents.d.ts +167 -2
- package/src/agents.js +912 -45
- package/src/catalogue.d.ts +60 -0
- package/src/catalogue.js +791 -0
- package/src/cli.js +10 -7
- package/src/config.d.ts +53 -4
- package/src/config.js +30 -5
- package/src/goals.d.ts +1 -1
- package/src/goals.js +14 -1
- package/src/manual.js +24 -2
- package/src/mime.d.ts +78 -0
- package/src/mime.js +342 -0
- package/src/net.d.ts +11 -0
- package/src/net.js +29 -2
- package/src/pine.js +10 -1
- package/src/router.js +3 -3
- package/src/sandbox-linux.d.ts +3 -1
- package/src/sandbox-linux.js +5 -0
- package/src/security.d.ts +22 -6
- package/src/security.js +44 -13
- package/src/slots.d.ts +106 -0
- package/src/slots.js +250 -0
- package/src/source-types.d.ts +20 -0
- package/src/sources/calendar.d.ts +24 -0
- package/src/sources/calendar.js +265 -0
- package/src/sources/command.js +109 -4
- package/src/sources/discord.d.ts +4 -0
- package/src/sources/discord.js +298 -0
- package/src/sources/feed.d.ts +19 -0
- package/src/sources/feed.js +257 -0
- package/src/sources/http.js +154 -103
- package/src/sources/mail.d.ts +51 -0
- package/src/sources/mail.js +1013 -0
- package/src/sources/matrix.d.ts +4 -0
- package/src/sources/matrix.js +232 -0
- package/src/sources/modbus.d.ts +15 -0
- package/src/sources/modbus.js +240 -0
- package/src/sources/onvif.d.ts +35 -0
- package/src/sources/onvif.js +326 -0
- package/src/sources/presence.d.ts +80 -0
- package/src/sources/presence.js +480 -0
- package/src/sources/serial.d.ts +21 -0
- package/src/sources/serial.js +220 -0
- package/src/sources/slack.d.ts +16 -0
- package/src/sources/slack.js +1062 -0
- package/src/sources/smtp.d.ts +4 -0
- package/src/sources/smtp.js +360 -0
- package/src/sources/stream.d.ts +68 -0
- package/src/sources/stream.js +534 -0
- package/src/sources/syslog.d.ts +32 -0
- package/src/sources/syslog.js +243 -0
- package/src/sources/system.d.ts +14 -0
- package/src/sources/system.js +236 -0
- package/src/sources/system.swift +102 -0
- package/src/sources/telegram.js +34 -1
- package/src/sources.d.ts +41 -1
- package/src/sources.js +147 -24
- package/src/tools.d.ts +1 -1
- package/src/tools.js +304 -23
- package/src/tui/app.d.ts +35 -2
- package/src/tui/app.js +306 -43
- package/src/tui/levels.d.ts +68 -0
- package/src/tui/levels.js +273 -0
- package/src/tui/picture.d.ts +17 -1
- package/src/tui/picture.js +72 -5
- package/src/types.d.ts +3 -0
- package/src/update.d.ts +9 -1
- package/src/update.js +75 -3
- package/src/watching.d.ts +156 -0
- package/src/watching.js +609 -4
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import net from "node:net";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import { fetch } from "undici";
|
|
5
|
+
import { isLocalHost, publicOnlyAgent } from "../net.js";
|
|
6
|
+
import { errText } from "../util.js";
|
|
7
|
+
import { capped, clip } from "../watching.js";
|
|
8
|
+
/**
|
|
9
|
+
* A network camera's own detections, as it reports them through ONVIF: motion, a person, a
|
|
10
|
+
* vehicle, tampering, a line crossed, a doorbell's button. For cameras and recorders that speak
|
|
11
|
+
* ONVIF (most that are not tied to a cloud do).
|
|
12
|
+
*
|
|
13
|
+
* options: { host, user, password, port?, path?, topics?, perMinute?, local? }
|
|
14
|
+
* port the camera's ONVIF port (80 by default; 8000, 8080, 8899 or 2020 on some makes)
|
|
15
|
+
* path where its device service is ("/onvif/device_service" by default)
|
|
16
|
+
* topics only events whose topic contains one of these words: ["Motion", "Person"]
|
|
17
|
+
* perMinute at most this many reports a minute (20 by default)
|
|
18
|
+
*
|
|
19
|
+
* event "event": { topic, source, data, time?, active?, dropped? }
|
|
20
|
+
*
|
|
21
|
+
* pine asks the camera for a subscription and then keeps asking it what happened (a "pull
|
|
22
|
+
* point"): the camera needs no way to reach pine. Every request goes to the host and port that
|
|
23
|
+
* were confirmed, whatever address the camera names in its answers. A camera says which state
|
|
24
|
+
* each thing is in when a subscription starts; that is the starting point, and only a change
|
|
25
|
+
* from it is reported. Nothing on the camera is changed.
|
|
26
|
+
*/
|
|
27
|
+
const NS = {
|
|
28
|
+
soap: "http://www.w3.org/2003/05/soap-envelope",
|
|
29
|
+
wsa: "http://www.w3.org/2005/08/addressing",
|
|
30
|
+
wsse: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
|
|
31
|
+
wsu: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd",
|
|
32
|
+
digest: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest",
|
|
33
|
+
base64: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary",
|
|
34
|
+
tds: "http://www.onvif.org/ver10/device/wsdl",
|
|
35
|
+
tev: "http://www.onvif.org/ver10/events/wsdl",
|
|
36
|
+
wsnt: "http://docs.oasis-open.org/wsn/b-2",
|
|
37
|
+
};
|
|
38
|
+
const ACTION = {
|
|
39
|
+
time: `${NS.tds}/GetSystemDateAndTime`,
|
|
40
|
+
capabilities: `${NS.tds}/GetCapabilities`,
|
|
41
|
+
create: `${NS.tev}/EventPortType/CreatePullPointSubscriptionRequest`,
|
|
42
|
+
pull: `${NS.tev}/PullPointSubscription/PullMessagesRequest`,
|
|
43
|
+
renew: "http://docs.oasis-open.org/wsn/bw-2/SubscriptionManager/RenewRequest",
|
|
44
|
+
unsubscribe: "http://docs.oasis-open.org/wsn/bw-2/SubscriptionManager/UnsubscribeRequest",
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* The pauses and waits, in one place. A test shortens them.
|
|
48
|
+
* retryMs, retryMaxMs before a new subscription after a failure: the first pause, and the longest
|
|
49
|
+
* waitSec how long the camera may hold one question open when nothing happens
|
|
50
|
+
* leaseSec how long a subscription lives unless it is renewed (it is, at half that time)
|
|
51
|
+
* idleMs the pause after an answer that came at once and was empty
|
|
52
|
+
*/
|
|
53
|
+
export const timing = { retryMs: 2000, retryMaxMs: 5 * 60_000, waitSec: 30, leaseSec: 600, idleMs: 1000 };
|
|
54
|
+
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
55
|
+
const esc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
56
|
+
const unesc = (s) => s.replace(/&(#x?[0-9a-f]+|amp|lt|gt|quot|apos);/gi, (all, name) => {
|
|
57
|
+
const n = name.toLowerCase();
|
|
58
|
+
if (n[0] !== "#")
|
|
59
|
+
return ENTITIES[n] ?? all;
|
|
60
|
+
const code = n[1] === "x" ? Number.parseInt(n.slice(2), 16) : Number.parseInt(n.slice(1), 10);
|
|
61
|
+
return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : all;
|
|
62
|
+
});
|
|
63
|
+
/** Text from a camera as an event carries it: one line, no control characters, not longer than `n`. */
|
|
64
|
+
const clean = (s, n) => clip(unesc(s).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim(), n);
|
|
65
|
+
/** The first element with this local name, whatever prefix the camera gives its namespace: its attributes and what is inside. */
|
|
66
|
+
export function element(xml, name) {
|
|
67
|
+
const m = new RegExp(`<(?:[\\w.-]+:)?${name}\\b([^>]*?)(?:/>|>([\\s\\S]*?)</(?:[\\w.-]+:)?${name}\\s*>)`).exec(xml);
|
|
68
|
+
return m ? { attrs: m[1] ?? "", inner: m[2] ?? "" } : undefined;
|
|
69
|
+
}
|
|
70
|
+
const attrs = (text) => Object.fromEntries([...text.matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)].map((m) => [m[1].replace(/^.*:/, ""), m[2] ?? m[3] ?? ""]));
|
|
71
|
+
/** The name → value pairs of a part of a notification (its Source, its Data). A few of them, each of a sensible length. */
|
|
72
|
+
function items(xml) {
|
|
73
|
+
const out = {};
|
|
74
|
+
for (const m of (xml ?? "").matchAll(/<(?:[\w.-]+:)?SimpleItem\b([^>]*?)\/?>/g)) {
|
|
75
|
+
const a = attrs(m[1]);
|
|
76
|
+
if (!a.Name || Object.keys(out).length >= 12)
|
|
77
|
+
continue;
|
|
78
|
+
out[clean(a.Name, 80)] = clean(a.Value ?? "", 200);
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
/** The notifications in an answer to PullMessages. */
|
|
83
|
+
export function notifications(xml) {
|
|
84
|
+
const out = [];
|
|
85
|
+
for (const m of xml.matchAll(/<(?:[\w.-]+:)?NotificationMessage\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?NotificationMessage\s*>/g)) {
|
|
86
|
+
const body = m[1];
|
|
87
|
+
// "tns1:RuleEngine/CellMotionDetector/Motion": the prefixes say nothing to a reader.
|
|
88
|
+
const topic = clean(element(body, "Topic")?.inner ?? "", 200)
|
|
89
|
+
.split("/")
|
|
90
|
+
.map((p) => p.replace(/^[\w.-]+:/, "").replace(/[^\w.-]/g, ""))
|
|
91
|
+
.filter(Boolean)
|
|
92
|
+
.join("/");
|
|
93
|
+
if (!topic)
|
|
94
|
+
continue;
|
|
95
|
+
const message = /<(?:[\w.-]+:)?Message\b([^>]*\b(?:UtcTime|PropertyOperation)\s*=[^>]*)>/.exec(body);
|
|
96
|
+
const a = attrs(message?.[1] ?? "");
|
|
97
|
+
const data = {};
|
|
98
|
+
for (const [k, v] of Object.entries(items(element(body, "Data")?.inner)))
|
|
99
|
+
data[k] = v === "true" ? true : v === "false" ? false : /^-?\d+(\.\d+)?$/.test(v) ? Number(v) : v;
|
|
100
|
+
out.push({ topic, source: items(element(body, "Source")?.inner), data, ...(a.UtcTime ? { time: clean(a.UtcTime, 40) } : {}), ...(a.PropertyOperation ? { operation: clean(a.PropertyOperation, 20) } : {}) });
|
|
101
|
+
if (out.length >= 50)
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
/** The WS-Security header a camera checks: the password is never sent, only a digest over a nonce, the time and the password. */
|
|
107
|
+
export function security(user, password, now, nonce = crypto.randomBytes(16)) {
|
|
108
|
+
const created = now.toISOString().replace(/\.\d+Z$/, "Z");
|
|
109
|
+
const digest = crypto.createHash("sha1").update(Buffer.concat([nonce, Buffer.from(created), Buffer.from(password)])).digest("base64");
|
|
110
|
+
return `<Security s:mustUnderstand="1" xmlns="${NS.wsse}"><UsernameToken><Username>${esc(user)}</Username><Password Type="${NS.digest}">${digest}</Password><Nonce EncodingType="${NS.base64}">${nonce.toString("base64")}</Nonce><Created xmlns="${NS.wsu}">${created}</Created></UsernameToken></Security>`;
|
|
111
|
+
}
|
|
112
|
+
const hostOk = (host) => net.isIP(host) !== 0 || /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(host);
|
|
113
|
+
const pathOk = (p) => /^\/[A-Za-z0-9_./~%-]{0,199}$/.test(p);
|
|
114
|
+
const words = (raw) => (Array.isArray(raw) ? raw : raw === undefined || raw === "" ? [] : String(raw).split(",")).map((w) => String(w).trim()).filter(Boolean);
|
|
115
|
+
export const type = {
|
|
116
|
+
summary: "a network camera's own detections over ONVIF: motion, a person, a vehicle, tampering, a doorbell's button. For cameras and recorders that speak ONVIF. It only listens",
|
|
117
|
+
options: Type.Object({
|
|
118
|
+
host: Type.String({ description: "the camera's address on the network, e.g. 192.168.1.40" }),
|
|
119
|
+
user: Type.String({ description: "the user name of an account on the camera" }),
|
|
120
|
+
password: Type.String({ description: "that account's password", secret: true }),
|
|
121
|
+
port: Type.Optional(Type.Number({ description: "the camera's ONVIF port. Default 80; some makes use 8000 (Reolink, Dahua), 8899 or 2020 (Tapo)" })),
|
|
122
|
+
path: Type.Optional(Type.String({ description: 'where the camera\'s ONVIF device service is. Default "/onvif/device_service", which nearly all use' })),
|
|
123
|
+
topics: Type.Optional(Type.Array(Type.String(), { description: 'only events whose topic contains one of these words, capitals do not matter, e.g. ["Motion", "Person", "Tamper"]. Without it everything the camera reports' })),
|
|
124
|
+
perMinute: Type.Optional(Type.Number({ description: "at most this many reports a minute; the rest are dropped and counted. Default 20" })),
|
|
125
|
+
local: Type.Optional(Type.Boolean({ description: "true if the address is a name on your owner's own network that does not say so (camera.lan). Not needed for an IP address or a .local name" })),
|
|
126
|
+
}, { additionalProperties: false }),
|
|
127
|
+
plan(o) {
|
|
128
|
+
const host = String(o.host ?? "").trim();
|
|
129
|
+
if (!hostOk(host))
|
|
130
|
+
throw new Error(`"${host}" is not an address. A camera's looks like 192.168.1.40 (without http:// and without a port: that is "port")`);
|
|
131
|
+
const port = o.port ?? 80;
|
|
132
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
133
|
+
throw new Error('"port" must be a port number. ONVIF is on 80 for most cameras, on 8000, 8899 or 2020 for some');
|
|
134
|
+
if (o.path !== undefined && !pathOk(String(o.path)))
|
|
135
|
+
throw new Error('"path" is a path on the camera, e.g. "/onvif/device_service"');
|
|
136
|
+
if (o.user !== undefined && !String(o.user).trim())
|
|
137
|
+
throw new Error('needs "user": the name of an account on the camera');
|
|
138
|
+
const topics = words(o.topics);
|
|
139
|
+
if (topics.length > 20 || topics.some((t) => t.length > 60))
|
|
140
|
+
throw new Error('"topics" is up to 20 short words, e.g. ["Motion", "Person"]');
|
|
141
|
+
if (o.perMinute !== undefined && !(Number.isInteger(o.perMinute) && o.perMinute >= 1 && o.perMinute <= 120))
|
|
142
|
+
throw new Error('"perMinute" is a whole number from 1 to 120');
|
|
143
|
+
return {
|
|
144
|
+
options: { ...o, host, ...(topics.length ? { topics } : {}) },
|
|
145
|
+
does: [
|
|
146
|
+
`connect to the camera at ${host}:${port}${o.local || isLocalHost(host) ? " (an address on your own network or this computer)" : ""} as ${o.user} and report what it detects${topics.length ? ` (topics with ${topics.join(", ")})` : ""}, at most ${o.perMinute ?? 20} times a minute`,
|
|
147
|
+
"with the password given, sent only to that camera and never in the clear",
|
|
148
|
+
"it only listens: nothing on the camera is changed",
|
|
149
|
+
],
|
|
150
|
+
opens: true,
|
|
151
|
+
tell: "The state the camera is in now is the starting point; it reports from the next change on. The sources tool shows whether the camera took the subscription.",
|
|
152
|
+
};
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
export default function onvif(source) {
|
|
156
|
+
const o = source.options;
|
|
157
|
+
const host = String(o.host ?? "").trim();
|
|
158
|
+
if (!hostOk(host))
|
|
159
|
+
throw new Error(`needs "host": the camera's address, e.g. 192.168.1.40`);
|
|
160
|
+
const port = Number(o.port ?? 80);
|
|
161
|
+
const user = String(o.user ?? "");
|
|
162
|
+
const password = String(o.password ?? "");
|
|
163
|
+
const devicePath = String(o.path ?? "/onvif/device_service");
|
|
164
|
+
if (!pathOk(devicePath))
|
|
165
|
+
throw new Error('"path" is a path on the camera, e.g. "/onvif/device_service"');
|
|
166
|
+
source.secret(password || undefined);
|
|
167
|
+
const wanted = words(o.topics).map((t) => t.toLowerCase());
|
|
168
|
+
const cap = capped(Number(o.perMinute ?? 20));
|
|
169
|
+
const stop = new AbortController();
|
|
170
|
+
const guard = o.local === true || isLocalHost(host) ? undefined : publicOnlyAgent((timing.waitSec + 20) * 1000);
|
|
171
|
+
const base = `http://${net.isIPv6(host) ? `[${host}]` : host}:${port}`;
|
|
172
|
+
/** A pause that ends with the source. */
|
|
173
|
+
const pause = (ms) => new Promise((resolve) => {
|
|
174
|
+
const done = () => {
|
|
175
|
+
clearTimeout(timer);
|
|
176
|
+
stop.signal.removeEventListener("abort", done);
|
|
177
|
+
resolve();
|
|
178
|
+
};
|
|
179
|
+
const timer = setTimeout(done, ms);
|
|
180
|
+
stop.signal.addEventListener("abort", done, { once: true });
|
|
181
|
+
});
|
|
182
|
+
/** How far the camera's clock is from this one: a camera refuses a digest made with a time that is not its own. */
|
|
183
|
+
let skew = 0;
|
|
184
|
+
let reported = 0;
|
|
185
|
+
/** Where an address the camera named is asked: on the host that was confirmed, at the path the camera gave. */
|
|
186
|
+
const here = (address, fallback) => {
|
|
187
|
+
try {
|
|
188
|
+
const u = new URL(unesc(String(address ?? "").trim()), base);
|
|
189
|
+
const p = `${u.pathname}${u.search}`;
|
|
190
|
+
return p.length <= 400 && /^\/[\x21-\x7e]*$/.test(p) ? p : fallback;
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return fallback;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
const call = async (at, action, body, opts = {}) => {
|
|
197
|
+
const header = `<a:Action s:mustUnderstand="1">${action}</a:Action><a:MessageID>urn:uuid:${crypto.randomUUID()}</a:MessageID><a:ReplyTo><a:Address>${NS.wsa}/anonymous</a:Address></a:ReplyTo><a:To s:mustUnderstand="1">${esc(base + at)}</a:To>${opts.reference ?? ""}${opts.auth !== false && user ? security(user, password, new Date(Date.now() + skew)) : ""}`;
|
|
198
|
+
const res = await fetch(base + at, {
|
|
199
|
+
method: "POST",
|
|
200
|
+
headers: { "content-type": `application/soap+xml; charset=utf-8; action="${action}"` },
|
|
201
|
+
body: `<?xml version="1.0" encoding="UTF-8"?><s:Envelope xmlns:s="${NS.soap}" xmlns:a="${NS.wsa}"><s:Header>${header}</s:Header><s:Body>${body}</s:Body></s:Envelope>`,
|
|
202
|
+
redirect: "manual",
|
|
203
|
+
signal: AbortSignal.any([stop.signal, AbortSignal.timeout(opts.timeoutMs ?? 15_000)]),
|
|
204
|
+
...(guard ? { dispatcher: guard } : {}),
|
|
205
|
+
});
|
|
206
|
+
const text = (await res.text()).slice(0, 512 * 1024);
|
|
207
|
+
const fault = element(text, "Fault");
|
|
208
|
+
if (fault || !res.ok) {
|
|
209
|
+
// What the camera says in a fault is its own text: it goes into the log, and a sentence of pine's into the status.
|
|
210
|
+
const said = clean((fault ? (element(fault.inner, "Text")?.inner ?? element(fault.inner, "faultstring")?.inner ?? "") : "").replace(/<[^>]+>/g, " "), 200);
|
|
211
|
+
source.log.debug(`${action.split("/").pop()} failed: HTTP ${res.status} ${said}`);
|
|
212
|
+
if (res.status === 401 || /not\s*authori[sz]ed|unauthori[sz]ed|authentication|FailedAuthentication/i.test(text))
|
|
213
|
+
throw Object.assign(new Error("the camera refused the user name or the password"), { auth: true });
|
|
214
|
+
throw new Error(fault ? "the camera answered with a fault" : `the camera answered ${res.status}`);
|
|
215
|
+
}
|
|
216
|
+
return text;
|
|
217
|
+
};
|
|
218
|
+
/** One subscription, from asking for it until it fails or the source stops. `alive` is called when the camera has answered a question about events. */
|
|
219
|
+
const session = async (alive) => {
|
|
220
|
+
// Without the password: every camera tells the time to anyone, so that a digest can be made at all.
|
|
221
|
+
try {
|
|
222
|
+
const t = element(await call(devicePath, ACTION.time, `<GetSystemDateAndTime xmlns="${NS.tds}"/>`, { auth: false }), "UTCDateTime")?.inner ?? "";
|
|
223
|
+
const n = (name) => Number(element(t, name)?.inner ?? Number.NaN);
|
|
224
|
+
const utc = Date.UTC(n("Year"), n("Month") - 1, n("Day"), n("Hour"), n("Minute"), n("Second"));
|
|
225
|
+
skew = Number.isFinite(utc) ? utc - Date.now() : 0;
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
if (stop.signal.aborted)
|
|
229
|
+
return;
|
|
230
|
+
skew = 0;
|
|
231
|
+
}
|
|
232
|
+
const caps = await call(devicePath, ACTION.capabilities, `<GetCapabilities xmlns="${NS.tds}"><Category>Events</Category></GetCapabilities>`);
|
|
233
|
+
const events = here(element(element(caps, "Events")?.inner ?? "", "XAddr")?.inner, "/onvif/Events");
|
|
234
|
+
const made = await call(events, ACTION.create, `<CreatePullPointSubscription xmlns="${NS.tev}"><InitialTerminationTime>PT${timing.leaseSec}S</InitialTerminationTime></CreatePullPointSubscription>`);
|
|
235
|
+
const ref = element(made, "SubscriptionReference")?.inner ?? "";
|
|
236
|
+
const at = here(element(ref, "Address")?.inner, events);
|
|
237
|
+
// Some cameras tell subscriptions apart by a parameter they want back in every header.
|
|
238
|
+
const params = element(ref, "ReferenceParameters")?.inner.trim() ?? "";
|
|
239
|
+
const reference = params.length <= 2000 ? params : "";
|
|
240
|
+
alive();
|
|
241
|
+
let renewAt = Date.now() + (timing.leaseSec * 1000) / 2;
|
|
242
|
+
try {
|
|
243
|
+
while (!stop.signal.aborted) {
|
|
244
|
+
const asked = Date.now();
|
|
245
|
+
const answer = await call(at, ACTION.pull, `<PullMessages xmlns="${NS.tev}"><Timeout>PT${timing.waitSec}S</Timeout><MessageLimit>10</MessageLimit></PullMessages>`, { reference, timeoutMs: (timing.waitSec + 15) * 1000 });
|
|
246
|
+
alive();
|
|
247
|
+
const got = notifications(answer);
|
|
248
|
+
for (const n of got)
|
|
249
|
+
take(n);
|
|
250
|
+
source.status(`subscribed to the camera, ${reported} event${reported === 1 ? "" : "s"} reported`);
|
|
251
|
+
if (Date.now() >= renewAt) {
|
|
252
|
+
await call(at, ACTION.renew, `<Renew xmlns="${NS.wsnt}"><TerminationTime>PT${timing.leaseSec}S</TerminationTime></Renew>`, { reference });
|
|
253
|
+
renewAt = Date.now() + (timing.leaseSec * 1000) / 2;
|
|
254
|
+
}
|
|
255
|
+
// A camera that answers at once with nothing is not asked in a tight loop.
|
|
256
|
+
if (!got.length && Date.now() - asked < timing.idleMs)
|
|
257
|
+
await pause(timing.idleMs);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
finally {
|
|
261
|
+
// Told that nobody listens any more, where there is still time to say so; it runs out by itself otherwise.
|
|
262
|
+
if (stop.signal.aborted)
|
|
263
|
+
void fetchQuietly(at, reference);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
const fetchQuietly = async (at, reference) => {
|
|
267
|
+
try {
|
|
268
|
+
const header = `<a:Action s:mustUnderstand="1">${ACTION.unsubscribe}</a:Action><a:MessageID>urn:uuid:${crypto.randomUUID()}</a:MessageID><a:To s:mustUnderstand="1">${esc(base + at)}</a:To>${reference}${user ? security(user, password, new Date(Date.now() + skew)) : ""}`;
|
|
269
|
+
await fetch(base + at, {
|
|
270
|
+
method: "POST",
|
|
271
|
+
headers: { "content-type": `application/soap+xml; charset=utf-8; action="${ACTION.unsubscribe}"` },
|
|
272
|
+
body: `<?xml version="1.0" encoding="UTF-8"?><s:Envelope xmlns:s="${NS.soap}" xmlns:a="${NS.wsa}"><s:Header>${header}</s:Header><s:Body><Unsubscribe xmlns="${NS.wsnt}"/></s:Body></s:Envelope>`,
|
|
273
|
+
redirect: "manual",
|
|
274
|
+
signal: AbortSignal.timeout(2000),
|
|
275
|
+
...(guard ? { dispatcher: guard } : {}),
|
|
276
|
+
}).then((r) => r.body?.cancel());
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
// it runs out by itself
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
const take = (n) => {
|
|
283
|
+
if (wanted.length && !wanted.some((w) => n.topic.toLowerCase().includes(w)))
|
|
284
|
+
return;
|
|
285
|
+
// A state (the camera says so with an operation) is kept per topic and thing, and only a change of it is a report.
|
|
286
|
+
if (n.operation) {
|
|
287
|
+
const slot = `state:${crypto.createHash("sha1").update(`${n.topic}\n${JSON.stringify(Object.entries(n.source).sort())}`).digest("hex").slice(0, 20)}`;
|
|
288
|
+
if (/^deleted$/i.test(n.operation))
|
|
289
|
+
return void source.kv.set(slot, null);
|
|
290
|
+
const now = JSON.stringify(Object.entries(n.data).sort());
|
|
291
|
+
const was = source.kv.get(slot) ?? undefined;
|
|
292
|
+
if (was === now)
|
|
293
|
+
return;
|
|
294
|
+
source.kv.set(slot, now);
|
|
295
|
+
// What it says when the subscription begins is where things stand, not something that happened;
|
|
296
|
+
// unless pine knew it otherwise, and it changed while nobody listened.
|
|
297
|
+
if (/^initiali[sz]ed$/i.test(n.operation) && was === undefined)
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
if (!cap.ok())
|
|
301
|
+
return;
|
|
302
|
+
const dropped = cap.dropped();
|
|
303
|
+
const flags = Object.values(n.data).filter((v) => typeof v === "boolean");
|
|
304
|
+
reported++;
|
|
305
|
+
source.emit("event", { topic: n.topic, source: n.source, data: n.data, ...(n.time ? { time: n.time } : {}), ...(flags.length === 1 ? { active: flags[0] } : {}), ...(dropped ? { dropped } : {}) });
|
|
306
|
+
};
|
|
307
|
+
source.status("connecting to the camera");
|
|
308
|
+
let wait = timing.retryMs;
|
|
309
|
+
const run = async () => {
|
|
310
|
+
while (!stop.signal.aborted) {
|
|
311
|
+
try {
|
|
312
|
+
await session(() => (wait = timing.retryMs));
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
if (stop.signal.aborted)
|
|
316
|
+
return;
|
|
317
|
+
source.log.warn("lost the camera", errText(e));
|
|
318
|
+
source.status(`${e?.auth ? "the camera refused the user name or the password" : "no connection to the camera"}; trying again every ${Math.round(wait / 1000)} s`);
|
|
319
|
+
}
|
|
320
|
+
await pause(wait);
|
|
321
|
+
wait = Math.min(wait * 2, timing.retryMaxMs);
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
void run();
|
|
325
|
+
source.onStop(() => stop.abort());
|
|
326
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { SourceType } from "../source-types.ts";
|
|
2
|
+
import type { SourceApi } from "../sources.ts";
|
|
3
|
+
/** How long one device is given to answer, and how long answers to a question about services are waited for. A test shortens them. */
|
|
4
|
+
export declare const timing: {
|
|
5
|
+
probeMs: number;
|
|
6
|
+
listenMs: number;
|
|
7
|
+
};
|
|
8
|
+
export interface DnsRecord {
|
|
9
|
+
name: string[];
|
|
10
|
+
type: number;
|
|
11
|
+
ttl: number;
|
|
12
|
+
/** PTR: the name it points at. */
|
|
13
|
+
ptr?: string[];
|
|
14
|
+
/** SRV: where the service is. */
|
|
15
|
+
srv?: {
|
|
16
|
+
port: number;
|
|
17
|
+
target: string[];
|
|
18
|
+
};
|
|
19
|
+
/** A, AAAA */
|
|
20
|
+
address?: string;
|
|
21
|
+
}
|
|
22
|
+
/** A question "who has a PTR record for these names". `unicast` asks for the answer to be sent back to the asker alone. */
|
|
23
|
+
export declare function dnsQuery(names: string[], unicast?: boolean): Buffer;
|
|
24
|
+
/**
|
|
25
|
+
* The records of a DNS message: answers, authority and additional ones alike. Anybody on the
|
|
26
|
+
* network can send one, so nothing in it is believed to be well formed: a name that points in
|
|
27
|
+
* circles, a length that leads out of the message or a record of an odd size ends the reading,
|
|
28
|
+
* and what was read until then is what comes back.
|
|
29
|
+
*/
|
|
30
|
+
export declare function dnsRead(buf: Buffer): {
|
|
31
|
+
response: boolean;
|
|
32
|
+
records: DnsRecord[];
|
|
33
|
+
};
|
|
34
|
+
/** A line of the system's Bonjour browser (`dns-sd -B`): a device of a kind appeared ("Add") or is gone ("Rmv"), on one network interface. */
|
|
35
|
+
export declare function browseLine(line: string): {
|
|
36
|
+
add: boolean;
|
|
37
|
+
iface: string;
|
|
38
|
+
service: string;
|
|
39
|
+
name: string;
|
|
40
|
+
} | undefined;
|
|
41
|
+
export interface Known {
|
|
42
|
+
there: boolean;
|
|
43
|
+
/** When it last answered. */
|
|
44
|
+
last?: number;
|
|
45
|
+
/** When it was found gone: the time it had last answered. */
|
|
46
|
+
left?: number;
|
|
47
|
+
name: string;
|
|
48
|
+
address?: string;
|
|
49
|
+
service?: string;
|
|
50
|
+
}
|
|
51
|
+
export interface Change {
|
|
52
|
+
event: "arrived" | "left";
|
|
53
|
+
payload: {
|
|
54
|
+
name: string;
|
|
55
|
+
address?: string;
|
|
56
|
+
service?: string;
|
|
57
|
+
awayFor?: number;
|
|
58
|
+
lastSeen?: string;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Turns "it answered" and "it did not" into arrivals and departures. A device that answered is
|
|
63
|
+
* there. One that does not is still there until it has been silent for `awayMs`: a phone that
|
|
64
|
+
* sleeps answers only now and then. `quiet` is for the look that is the starting point: what is
|
|
65
|
+
* found is noted and nothing is reported.
|
|
66
|
+
*/
|
|
67
|
+
export declare function tracker(awayMs: number, state?: Record<string, Known>): {
|
|
68
|
+
state: Record<string, Known>;
|
|
69
|
+
sight(key: string, seen: boolean, now: number, quiet: boolean, info: {
|
|
70
|
+
name: string;
|
|
71
|
+
address?: string;
|
|
72
|
+
service?: string;
|
|
73
|
+
}): Change | undefined;
|
|
74
|
+
/** It said goodbye, or was silent for long enough. */
|
|
75
|
+
gone(key: string): Change | undefined;
|
|
76
|
+
};
|
|
77
|
+
/** Whether anything is at this address right now: it answers a ping, or it answers a connection, be it with a no. */
|
|
78
|
+
export declare function answers(ip: string): Promise<boolean>;
|
|
79
|
+
export declare const type: SourceType;
|
|
80
|
+
export default function presence(source: SourceApi): Promise<void>;
|