node-red-contrib-unifi-ultimate 1.1.9 → 1.1.11
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
CHANGED
|
@@ -126,16 +126,21 @@ Things you can do:
|
|
|
126
126
|
- Play or stop a siren, control relay outputs, and test speaker or siren sound.
|
|
127
127
|
- Read and select Protect Arm Profiles, then arm or disarm the local Alarm Manager from the NVR control.
|
|
128
128
|
|
|
129
|
-
### Automatic KNX AI camera adapter
|
|
129
|
+
### Automatic Cerebrum / KNX AI camera adapter
|
|
130
130
|
|
|
131
|
-
|
|
131
|
+
Every configured **Unifi Protect Config** instance automatically publishes its cameras through the shared `node-red.knx-ai.camera-adapters.v1` runtime contract. Cerebrum and KNX AI can discover the installed provider without a Protect Device node, camera selector, or intermediate wire. They can then:
|
|
132
132
|
|
|
133
|
-
- send a current camera snapshot to
|
|
133
|
+
- send a current camera snapshot to the chat channel;
|
|
134
134
|
- describe a fresh snapshot with the configured vision-capable LLM;
|
|
135
|
-
-
|
|
136
|
-
- filter smart events by
|
|
135
|
+
- subscribe to motion, line-crossing, intrusion-zone and loiter-zone events;
|
|
136
|
+
- filter smart events by classifications such as people, animals, vehicles, faces, license plates and packages, and by an exact Protect line or zone;
|
|
137
|
+
- search recorded events with time, camera and detection filters, follow explicit pagination, and retrieve the thumbnail belonging to an exact returned event.
|
|
138
|
+
|
|
139
|
+
Recorded history requires the optional **History user/password** in the Protect config node. Use a dedicated local UniFi OS account that can view the required cameras. The Integration API key remains responsible for the official live-event and current-snapshot endpoints; the local account opens only the separate recorded-history session. Credentials and session cookies stay in the Node-RED credential/config node and are never published to Cerebrum, KNX AI, flows or chat context.
|
|
140
|
+
|
|
141
|
+
Other camera packages can implement the same catalog, event, snapshot and recorded-history methods without adding vendor-specific code to Cerebrum.
|
|
142
|
+
|
|
137
143
|
|
|
138
|
-
The integration uses the generic `node-red.knx-ai.camera-adapters.v1` runtime contract, so other camera packages can register the same catalog/snapshot/event capabilities without vendor-specific code in KNX AI. Protect API keys remain inside this config node and are never copied into KNX AI.
|
|
139
144
|
|
|
140
145
|
<br/>
|
|
141
146
|
<br/>
|
|
@@ -21,7 +21,9 @@
|
|
|
21
21
|
rejectUnauthorized: { value: false }
|
|
22
22
|
},
|
|
23
23
|
credentials: {
|
|
24
|
-
apiKey: { type: "password", required: true }
|
|
24
|
+
apiKey: { type: "password", required: true },
|
|
25
|
+
historyUsername: { type: "text" },
|
|
26
|
+
historyPassword: { type: "password" }
|
|
25
27
|
},
|
|
26
28
|
label: function () {
|
|
27
29
|
return this.name || this.host || "Unifi Protect Config";
|
|
@@ -31,9 +33,13 @@
|
|
|
31
33
|
const $hostInput = $("#node-config-input-host");
|
|
32
34
|
const $port = $("#node-config-input-port");
|
|
33
35
|
const $apiKey = $("#node-config-input-apiKey");
|
|
36
|
+
const $historyUsername = $("#node-config-input-historyUsername");
|
|
34
37
|
const $allowSelfSigned = $("#node-config-input-allowSelfSigned");
|
|
35
38
|
const $portRow = $port.closest(".form-row");
|
|
36
39
|
const $apiKeyRow = $apiKey.closest(".form-row");
|
|
40
|
+
const $historyUsernameRow = $historyUsername.closest(".form-row");
|
|
41
|
+
const $historyPasswordRow = $("#node-config-input-historyPassword").closest(".form-row");
|
|
42
|
+
const $historyHintRow = $("#node-config-row-history-hint");
|
|
37
43
|
const $securityRow = $allowSelfSigned.closest(".form-row");
|
|
38
44
|
const $advancedRow = $("#node-config-row-advanced");
|
|
39
45
|
|
|
@@ -47,6 +53,9 @@
|
|
|
47
53
|
const hasHost = String($hostInput.val() || node.host || "").trim() !== "";
|
|
48
54
|
$portRow.toggle(hasHost);
|
|
49
55
|
$apiKeyRow.toggle(hasHost);
|
|
56
|
+
$historyUsernameRow.toggle(hasHost);
|
|
57
|
+
$historyPasswordRow.toggle(hasHost);
|
|
58
|
+
$historyHintRow.toggle(hasHost);
|
|
50
59
|
$securityRow.toggle(hasHost);
|
|
51
60
|
$advancedRow.toggle(hasHost);
|
|
52
61
|
}
|
|
@@ -94,6 +103,18 @@
|
|
|
94
103
|
<label for="node-config-input-apiKey"><i class="fa fa-key"></i> API Key</label>
|
|
95
104
|
<input type="password" id="node-config-input-apiKey" placeholder="Paste your UniFi Protect API key">
|
|
96
105
|
</div>
|
|
106
|
+
<div id="node-config-row-history-hint" class="form-row">
|
|
107
|
+
<label><i class="fa fa-history"></i> History</label>
|
|
108
|
+
<span>Optional local UniFi OS account for recorded events and event snapshots</span>
|
|
109
|
+
</div>
|
|
110
|
+
<div class="form-row">
|
|
111
|
+
<label for="node-config-input-historyUsername"><i class="fa fa-user"></i> History user</label>
|
|
112
|
+
<input type="text" id="node-config-input-historyUsername" autocomplete="username" placeholder="Local UniFi OS username">
|
|
113
|
+
</div>
|
|
114
|
+
<div class="form-row">
|
|
115
|
+
<label for="node-config-input-historyPassword"><i class="fa fa-lock"></i> History password</label>
|
|
116
|
+
<input type="password" id="node-config-input-historyPassword" autocomplete="current-password" placeholder="Local UniFi OS password">
|
|
117
|
+
</div>
|
|
97
118
|
<div class="form-row">
|
|
98
119
|
<label for="node-config-input-allowSelfSigned"><i class="fa fa-lock"></i> Security</label>
|
|
99
120
|
<input type="checkbox" id="node-config-input-allowSelfSigned" style="display:inline-block; width:auto; vertical-align:top;">
|
|
@@ -116,6 +137,7 @@
|
|
|
116
137
|
<p><b>Controller</b> accepts the UniFi OS host or IP address. The node builds the Protect integration URL automatically.</p>
|
|
117
138
|
<p><b>Port</b> is optional. Leave it empty to use the default <code>443</code>. Set it when your UniFi OS server listens on a custom port (for example <code>11443</code>). A port embedded directly in the Controller field (<code>host:port</code>) takes precedence over this field.</p>
|
|
118
139
|
<p><b>API Key</b> is required for authentication and is sent automatically as <code>X-API-Key</code>.</p>
|
|
140
|
+
<p><b>History user/password</b> are optional and enable recorded-event searches and event thumbnails for Cerebrum/KNX AI. Enter a dedicated <b>local UniFi OS account</b> that can view the required Protect cameras. The official Integration API key covers live events and current snapshots but does not expose the recorded-event archive. These credentials remain in the Node-RED credential store; the camera adapter never publishes them.</p>
|
|
119
141
|
<p><b>Security</b> — <b>Allow self-signed certificate</b> is enabled by default because UniFi controllers almost always present a self-signed certificate. Leave it checked for UniFi OS setups. Uncheck it only if your controller serves a certificate signed by a trusted certificate authority and you want strict verification.</p>
|
|
120
142
|
<p><b>Name</b> is the config node name shown in the editor.</p>
|
|
121
143
|
|
|
@@ -125,6 +147,6 @@
|
|
|
125
147
|
|
|
126
148
|
<h3>Automatic KNX AI camera adapter</h3>
|
|
127
149
|
<p>If <code>node-red-contrib-knx-ultimate</code> is installed, this config node automatically publishes its available cameras to the KNX AI chat runtime. No Protect Device node, camera selector, or wire to KNX AI is required.</p>
|
|
128
|
-
<p>KNX AI can request snapshots directly and subscribe to motion, smart line, intrusion-zone, and loiter-zone events. Persistent notification rules remain owned by the
|
|
150
|
+
<p>KNX AI and Cerebrum can request snapshots directly and subscribe to motion, smart line, intrusion-zone, and loiter-zone events. When the optional local history credentials are configured, they can also search recorded events with explicit pagination and retrieve the JPEG thumbnail belonging to an exact event. Persistent notification rules remain owned by the AI chat context. API keys, credentials, cookies, and raw controller responses stay private inside this config node.</p>
|
|
129
151
|
<p>The provider uses the generic <code>node-red.knx-ai.camera-adapters.v1</code> runtime contract, allowing other camera suites to expose the same capabilities independently.</p>
|
|
130
152
|
</script>
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const {
|
|
4
4
|
buildBaseUrlFromHost,
|
|
5
|
+
buildControllerBaseUrlFromHost,
|
|
5
6
|
normalizePort,
|
|
6
7
|
buildQueryString,
|
|
7
8
|
doRequest,
|
|
@@ -18,11 +19,18 @@ const {
|
|
|
18
19
|
summarizeDevice
|
|
19
20
|
} = require("./utils/unifi-protect-device-registry");
|
|
20
21
|
const {
|
|
22
|
+
SMART_CAMERA_EVENTS,
|
|
21
23
|
collectNamedScopes,
|
|
22
24
|
getKnxAiCameraRegistry,
|
|
23
25
|
normalizeProtectCameraEvent,
|
|
24
26
|
normalizeSearchText
|
|
25
27
|
} = require("./utils/knx-ai-camera-registry");
|
|
28
|
+
const {
|
|
29
|
+
createProtectHistoryPaginationGuard,
|
|
30
|
+
extractProtectHistorySessionHeaders,
|
|
31
|
+
normalizeProtectHistoryRequest,
|
|
32
|
+
selectProtectHistoryEvents
|
|
33
|
+
} = require("./utils/unifi-protect-history");
|
|
26
34
|
|
|
27
35
|
function extractProtectErrorDetail(response) {
|
|
28
36
|
let payload = response && response.payload;
|
|
@@ -81,7 +89,7 @@ module.exports = function(RED) {
|
|
|
81
89
|
id: "unifi-ultimate",
|
|
82
90
|
title: "UniFi Ultimate / Protect",
|
|
83
91
|
packageName: "node-red-contrib-unifi-ultimate",
|
|
84
|
-
capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines"]
|
|
92
|
+
capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines", "event_history", "event_snapshot"]
|
|
85
93
|
});
|
|
86
94
|
|
|
87
95
|
function UnifiProtectConfigNode(config) {
|
|
@@ -92,6 +100,7 @@ module.exports = function(RED) {
|
|
|
92
100
|
node.host = String(config.host || "").trim();
|
|
93
101
|
node.port = normalizePort(config.port);
|
|
94
102
|
node.baseUrl = buildBaseUrlFromHost(node.host, node.port);
|
|
103
|
+
node.controllerBaseUrl = buildControllerBaseUrlFromHost(node.host, node.port);
|
|
95
104
|
// UniFi controllers almost always use self-signed certificates, so accept
|
|
96
105
|
// them unless the user explicitly opted into strict verification.
|
|
97
106
|
node.rejectUnauthorized = config.rejectUnauthorized === true || config.rejectUnauthorized === "true";
|
|
@@ -101,10 +110,89 @@ module.exports = function(RED) {
|
|
|
101
110
|
node.reconnectTimer = null;
|
|
102
111
|
node.isClosing = false;
|
|
103
112
|
node.knxAiCameraCache = { at: 0, cameras: [] };
|
|
113
|
+
node.knxAiCameraRefresh = null;
|
|
114
|
+
node.knxAiCameraRefreshAgain = false;
|
|
104
115
|
node.knxAiCameraListeners = new Set();
|
|
116
|
+
node.protectHistorySessionHeaders = null;
|
|
117
|
+
node.protectHistoryAuthentication = null;
|
|
118
|
+
node.protectHistoryPaginationGuard = createProtectHistoryPaginationGuard();
|
|
105
119
|
|
|
106
120
|
node.getApiKey = () => node.credentials && node.credentials.apiKey;
|
|
107
121
|
|
|
122
|
+
node.getHistoryCredentials = () => ({
|
|
123
|
+
username: String(node.credentials && node.credentials.historyUsername || "").trim(),
|
|
124
|
+
password: String(node.credentials && node.credentials.historyPassword || "")
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
node.hasHistoryCredentials = () => {
|
|
128
|
+
const credentials = node.getHistoryCredentials();
|
|
129
|
+
return Boolean(credentials.username && credentials.password);
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
node.authenticateProtectHistory = async () => {
|
|
133
|
+
if (node.protectHistorySessionHeaders) return node.protectHistorySessionHeaders;
|
|
134
|
+
if (node.protectHistoryAuthentication) return node.protectHistoryAuthentication;
|
|
135
|
+
const authentication = Promise.resolve().then(async () => {
|
|
136
|
+
const credentials = node.getHistoryCredentials();
|
|
137
|
+
if (!credentials.username || !credentials.password) {
|
|
138
|
+
const error = new Error("UniFi Protect historical events require the optional local history username and password in the Protect config node.");
|
|
139
|
+
error.code = "UNIFI_PROTECT_HISTORY_CREDENTIALS_REQUIRED";
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
if (!node.controllerBaseUrl) throw new Error("The configured IP is empty or invalid.");
|
|
143
|
+
const headers = {
|
|
144
|
+
Accept: "application/json",
|
|
145
|
+
"Content-Type": "application/json"
|
|
146
|
+
};
|
|
147
|
+
const body = buildRequestBody(headers, "POST", {
|
|
148
|
+
username: credentials.username,
|
|
149
|
+
password: credentials.password,
|
|
150
|
+
rememberMe: false
|
|
151
|
+
});
|
|
152
|
+
const response = await doRequest(new URL(`${node.controllerBaseUrl}/api/auth/login`), {
|
|
153
|
+
method: "POST",
|
|
154
|
+
headers,
|
|
155
|
+
timeout: 15000,
|
|
156
|
+
rejectUnauthorized: node.rejectUnauthorized
|
|
157
|
+
}, body);
|
|
158
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
159
|
+
const detail = extractProtectErrorDetail(response);
|
|
160
|
+
const error = new Error(`UniFi OS login for Protect history failed (HTTP ${response.statusCode || "unknown"}${detail ? `: ${detail}` : ""}).`);
|
|
161
|
+
error.code = "UNIFI_PROTECT_HISTORY_LOGIN_FAILED";
|
|
162
|
+
error.statusCode = Number(response.statusCode) || 0;
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
node.protectHistorySessionHeaders = extractProtectHistorySessionHeaders(response);
|
|
166
|
+
return node.protectHistorySessionHeaders;
|
|
167
|
+
}).finally(() => {
|
|
168
|
+
if (node.protectHistoryAuthentication === authentication) node.protectHistoryAuthentication = null;
|
|
169
|
+
});
|
|
170
|
+
node.protectHistoryAuthentication = authentication;
|
|
171
|
+
return authentication;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
node.executeProtectHistoryRequest = async ({ path, method = "GET", query, headers, payload, timeout = 20000 } = {}, retryAuthentication = true) => {
|
|
175
|
+
const sessionHeaders = await node.authenticateProtectHistory();
|
|
176
|
+
const normalizedPath = String(path || "").replace(/^\/+/, "");
|
|
177
|
+
const requestUrl = new URL(`${node.controllerBaseUrl}/proxy/protect/api/${normalizedPath}${buildQueryString(query)}`);
|
|
178
|
+
const requestMethod = String(method || "GET").toUpperCase();
|
|
179
|
+
const requestHeaders = Object.assign({ Accept: "application/json" }, sessionHeaders, headers || {});
|
|
180
|
+
const requestBody = buildRequestBody(requestHeaders, requestMethod, payload);
|
|
181
|
+
const response = await doRequest(requestUrl, {
|
|
182
|
+
method: requestMethod,
|
|
183
|
+
headers: requestHeaders,
|
|
184
|
+
timeout,
|
|
185
|
+
rejectUnauthorized: node.rejectUnauthorized
|
|
186
|
+
}, requestBody);
|
|
187
|
+
const refreshedCsrf = response && response.headers && response.headers["x-csrf-token"];
|
|
188
|
+
if (refreshedCsrf && node.protectHistorySessionHeaders) node.protectHistorySessionHeaders["X-CSRF-Token"] = String(refreshedCsrf);
|
|
189
|
+
if (Number(response && response.statusCode) === 401 && retryAuthentication) {
|
|
190
|
+
node.protectHistorySessionHeaders = null;
|
|
191
|
+
return node.executeProtectHistoryRequest({ path, method, query, headers, payload, timeout }, false);
|
|
192
|
+
}
|
|
193
|
+
return response;
|
|
194
|
+
};
|
|
195
|
+
|
|
108
196
|
node.apiRequest = async ({
|
|
109
197
|
path,
|
|
110
198
|
method = "GET",
|
|
@@ -232,45 +320,76 @@ module.exports = function(RED) {
|
|
|
232
320
|
return getCapabilitiesForType(deviceType, selectedDevice);
|
|
233
321
|
};
|
|
234
322
|
|
|
235
|
-
node.listKnxAiCameras = async ({ force = false } = {}) => {
|
|
323
|
+
node.listKnxAiCameras = async ({ force = false, allowStale = false } = {}) => {
|
|
236
324
|
const now = Date.now();
|
|
237
|
-
|
|
325
|
+
const cachedCameras = Array.isArray(node.knxAiCameraCache.cameras)
|
|
326
|
+
? node.knxAiCameraCache.cameras.slice()
|
|
327
|
+
: [];
|
|
328
|
+
const cacheIsFresh = node.knxAiCameraCache.at > 0
|
|
329
|
+
&& (now - node.knxAiCameraCache.at) < 30000;
|
|
330
|
+
if (!force && cacheIsFresh) {
|
|
238
331
|
return node.knxAiCameraCache.cameras.slice();
|
|
239
332
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
camera && camera.
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
333
|
+
if (node.knxAiCameraRefresh) {
|
|
334
|
+
if (!force && allowStale && cachedCameras.length > 0) return cachedCameras;
|
|
335
|
+
return (await node.knxAiCameraRefresh).slice();
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
let refresh;
|
|
339
|
+
refresh = Promise.resolve().then(() => node.fetchDevices("camera")).then((devices) => {
|
|
340
|
+
const cameras = devices.map((camera) => {
|
|
341
|
+
const nativeCameraId = String(camera && camera.id || "").trim();
|
|
342
|
+
const cameraName = String(camera && (camera.name || camera.displayName) || nativeCameraId).trim();
|
|
343
|
+
const cameraState = String(camera && camera.state || "").trim().toUpperCase();
|
|
344
|
+
const objectTypes = Array.from(new Set([].concat(
|
|
345
|
+
camera && camera.smartDetectSettings && Array.isArray(camera.smartDetectSettings.objectTypes)
|
|
346
|
+
? camera.smartDetectSettings.objectTypes
|
|
347
|
+
: [],
|
|
348
|
+
camera && camera.featureFlags && Array.isArray(camera.featureFlags.smartDetectTypes)
|
|
349
|
+
? camera.featureFlags.smartDetectTypes
|
|
350
|
+
: []
|
|
351
|
+
).map((value) => String(value || "").trim()).filter(Boolean)));
|
|
352
|
+
return {
|
|
353
|
+
id: `${node.id}:${nativeCameraId}`,
|
|
354
|
+
cameraId: `${node.id}:${nativeCameraId}`,
|
|
355
|
+
nativeCameraId,
|
|
356
|
+
cameraName,
|
|
357
|
+
name: cameraName,
|
|
358
|
+
aliases: [cameraName, nativeCameraId].filter(Boolean),
|
|
359
|
+
controllerId: node.id,
|
|
360
|
+
controllerName: node.name || node.host || node.id,
|
|
361
|
+
adapterId: "unifi-ultimate",
|
|
362
|
+
adapterTitle: "UniFi Ultimate / Protect",
|
|
363
|
+
source: "unifi-ultimate",
|
|
364
|
+
state: cameraState,
|
|
365
|
+
online: cameraState ? cameraState === "CONNECTED" : null,
|
|
366
|
+
objectTypes,
|
|
367
|
+
lines: collectNamedScopes(camera, "line"),
|
|
368
|
+
zones: collectNamedScopes(camera, "zone"),
|
|
369
|
+
raw: camera
|
|
370
|
+
};
|
|
371
|
+
}).filter((camera) => camera.nativeCameraId);
|
|
372
|
+
node.knxAiCameraCache = { at: Date.now(), cameras };
|
|
373
|
+
return cameras;
|
|
374
|
+
}).finally(() => {
|
|
375
|
+
if (node.knxAiCameraRefresh !== refresh) return;
|
|
376
|
+
node.knxAiCameraRefresh = null;
|
|
377
|
+
if (!node.knxAiCameraRefreshAgain || node.isClosing) return;
|
|
378
|
+
node.knxAiCameraRefreshAgain = false;
|
|
379
|
+
node.knxAiCameraCache = { at: 0, cameras: node.knxAiCameraCache.cameras };
|
|
380
|
+
Promise.resolve(node.listKnxAiCameras({ force: true })).catch((error) => {
|
|
381
|
+
node.warn(`Unable to refresh the KNX AI camera catalog: ${error && error.message ? error.message : error}`);
|
|
382
|
+
});
|
|
383
|
+
});
|
|
384
|
+
node.knxAiCameraRefresh = refresh;
|
|
385
|
+
|
|
386
|
+
if (!force && allowStale && cachedCameras.length > 0) {
|
|
387
|
+
refresh.catch((error) => {
|
|
388
|
+
node.warn(`Unable to refresh the KNX AI camera catalog: ${error && error.message ? error.message : error}`);
|
|
389
|
+
});
|
|
390
|
+
return cachedCameras;
|
|
391
|
+
}
|
|
392
|
+
return (await refresh).slice();
|
|
274
393
|
};
|
|
275
394
|
|
|
276
395
|
node.resolveKnxAiCamera = async ({ cameraId, cameraName } = {}) => {
|
|
@@ -344,6 +463,130 @@ module.exports = function(RED) {
|
|
|
344
463
|
};
|
|
345
464
|
};
|
|
346
465
|
|
|
466
|
+
node.queryKnxAiCameraEvents = async (request = {}) => {
|
|
467
|
+
const normalized = normalizeProtectHistoryRequest(request);
|
|
468
|
+
const requestSource = request && typeof request === "object" && !Array.isArray(request) ? request : {};
|
|
469
|
+
const paginationKey = JSON.stringify({
|
|
470
|
+
cameraId: normalized.cameraId,
|
|
471
|
+
cameraName: normalized.cameraName,
|
|
472
|
+
start: requestSource.from !== undefined || requestSource.start !== undefined ? normalized.start : "default",
|
|
473
|
+
end: requestSource.to !== undefined || requestSource.end !== undefined ? normalized.end : "default",
|
|
474
|
+
eventTypes: normalized.eventTypes,
|
|
475
|
+
objectTypes: normalized.objectTypes
|
|
476
|
+
});
|
|
477
|
+
const requestedCamera = normalized.cameraId || normalized.cameraName
|
|
478
|
+
? await node.resolveKnxAiCamera({ cameraId: normalized.cameraId, cameraName: normalized.cameraName })
|
|
479
|
+
: null;
|
|
480
|
+
const response = await node.executeProtectHistoryRequest({
|
|
481
|
+
path: "events",
|
|
482
|
+
method: "GET",
|
|
483
|
+
query: normalized.query,
|
|
484
|
+
timeout: 25000
|
|
485
|
+
});
|
|
486
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
487
|
+
const detail = extractProtectErrorDetail(response);
|
|
488
|
+
throw new Error(`Unable to retrieve UniFi Protect historical events (HTTP ${response.statusCode || "unknown"}${detail ? `: ${detail}` : ""}).`);
|
|
489
|
+
}
|
|
490
|
+
const payload = Array.isArray(response.payload)
|
|
491
|
+
? response.payload
|
|
492
|
+
: response.payload && Array.isArray(response.payload.events)
|
|
493
|
+
? response.payload.events
|
|
494
|
+
: response.payload && Array.isArray(response.payload.data)
|
|
495
|
+
? response.payload.data
|
|
496
|
+
: [];
|
|
497
|
+
const cameras = await node.listKnxAiCameras();
|
|
498
|
+
const events = payload.map((item) => {
|
|
499
|
+
if (!item || typeof item !== "object") return null;
|
|
500
|
+
const nativeCameraId = String(item.device || item.camera || item.cameraId || "").trim();
|
|
501
|
+
const startValue = item.start === undefined || item.start === null ? item.timestamp : item.start;
|
|
502
|
+
const numericStart = Number(startValue);
|
|
503
|
+
const start = Number.isFinite(numericStart) ? numericStart : Date.parse(String(startValue || ""));
|
|
504
|
+
if (!nativeCameraId || !Number.isFinite(start)) return null;
|
|
505
|
+
const numericEnd = Number(item.end);
|
|
506
|
+
const parsedEnd = item.end === null || item.end === undefined
|
|
507
|
+
? null
|
|
508
|
+
: Number.isFinite(numericEnd)
|
|
509
|
+
? numericEnd
|
|
510
|
+
: Date.parse(String(item.end));
|
|
511
|
+
const camera = cameras.find((candidate) => candidate.nativeCameraId === nativeCameraId);
|
|
512
|
+
const event = normalizeProtectCameraEvent({
|
|
513
|
+
event: Object.assign({}, item, {
|
|
514
|
+
modelKey: "event",
|
|
515
|
+
type: item.type || item.eventType,
|
|
516
|
+
device: nativeCameraId,
|
|
517
|
+
start
|
|
518
|
+
}),
|
|
519
|
+
camera: camera && camera.raw,
|
|
520
|
+
controllerId: node.id,
|
|
521
|
+
controllerName: node.name || node.host || node.id
|
|
522
|
+
});
|
|
523
|
+
if (!event) return null;
|
|
524
|
+
return Object.assign({}, event, {
|
|
525
|
+
endAt: Number.isFinite(parsedEnd) ? new Date(parsedEnd).toISOString() : "",
|
|
526
|
+
score: Number.isFinite(Number(item.score)) ? Number(item.score) : null,
|
|
527
|
+
thumbnailAvailable: Boolean(item.thumbnail || item.thumbnailId)
|
|
528
|
+
});
|
|
529
|
+
}).filter(Boolean);
|
|
530
|
+
const selected = selectProtectHistoryEvents(events, Object.assign({}, normalized, {
|
|
531
|
+
cameraId: requestedCamera && requestedCamera.id || ""
|
|
532
|
+
}));
|
|
533
|
+
const continuation = node.protectHistoryPaginationGuard.evaluate({
|
|
534
|
+
key: paginationKey,
|
|
535
|
+
offset: normalized.offset,
|
|
536
|
+
pageSize: normalized.pageSize,
|
|
537
|
+
events: payload
|
|
538
|
+
});
|
|
539
|
+
return {
|
|
540
|
+
events: continuation.duplicatePage ? [] : selected,
|
|
541
|
+
from: normalized.from,
|
|
542
|
+
to: normalized.to,
|
|
543
|
+
offset: normalized.offset,
|
|
544
|
+
nextOffset: continuation.nextOffset,
|
|
545
|
+
hasMore: continuation.hasMore,
|
|
546
|
+
scannedEvents: payload.length,
|
|
547
|
+
duplicatePage: continuation.duplicatePage,
|
|
548
|
+
continuationStoppedReason: continuation.duplicatePage
|
|
549
|
+
? "duplicate_page"
|
|
550
|
+
: !continuation.madeProgress && payload.length >= normalized.pageSize
|
|
551
|
+
? "no_progress"
|
|
552
|
+
: ""
|
|
553
|
+
};
|
|
554
|
+
};
|
|
555
|
+
|
|
556
|
+
node.takeKnxAiCameraEventSnapshot = async ({ eventId } = {}) => {
|
|
557
|
+
const id = String(eventId || "").trim().replace(/^e-/, "");
|
|
558
|
+
if (!id || id.length > 200) throw new Error("A valid UniFi Protect event id is required.");
|
|
559
|
+
let response;
|
|
560
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
561
|
+
response = await node.executeProtectHistoryRequest({
|
|
562
|
+
path: `events/${encodeURIComponent(id)}/thumbnail`,
|
|
563
|
+
method: "GET",
|
|
564
|
+
headers: { Accept: "image/jpeg" },
|
|
565
|
+
timeout: 25000
|
|
566
|
+
});
|
|
567
|
+
if (response.statusCode !== 404 || attempt === 3) break;
|
|
568
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
569
|
+
}
|
|
570
|
+
if (!response || response.statusCode < 200 || response.statusCode >= 300) {
|
|
571
|
+
const detail = extractProtectErrorDetail(response);
|
|
572
|
+
throw new Error(`Unable to retrieve the UniFi Protect event snapshot (HTTP ${response && response.statusCode || "unknown"}${detail ? `: ${detail}` : ""}).`);
|
|
573
|
+
}
|
|
574
|
+
if (!Buffer.isBuffer(response.payload) || response.payload.length === 0) {
|
|
575
|
+
throw new Error("UniFi Protect returned an empty or invalid event snapshot.");
|
|
576
|
+
}
|
|
577
|
+
const contentTypeHeader = response.headers && response.headers["content-type"];
|
|
578
|
+
const mediaType = String(Array.isArray(contentTypeHeader) ? contentTypeHeader[0] : contentTypeHeader || "image/jpeg")
|
|
579
|
+
.split(";")[0]
|
|
580
|
+
.trim()
|
|
581
|
+
.toLowerCase();
|
|
582
|
+
return {
|
|
583
|
+
data: response.payload,
|
|
584
|
+
mediaType,
|
|
585
|
+
eventId: id,
|
|
586
|
+
statusCode: response.statusCode
|
|
587
|
+
};
|
|
588
|
+
};
|
|
589
|
+
|
|
347
590
|
node.buildWebSocketUrl = (path) => {
|
|
348
591
|
// Reuse the configured HTTPS base URL and only swap protocol for the
|
|
349
592
|
// matching websocket scheme.
|
|
@@ -526,12 +769,17 @@ module.exports = function(RED) {
|
|
|
526
769
|
id: `knx-ai-camera-adapter:${node.id}`,
|
|
527
770
|
handleProtectDeviceUpdate(update) {
|
|
528
771
|
const item = update && update.item;
|
|
529
|
-
if (item && item.modelKey === "camera")
|
|
772
|
+
if (item && item.modelKey === "camera") {
|
|
773
|
+
node.knxAiCameraCache = { at: 0, cameras: node.knxAiCameraCache.cameras };
|
|
774
|
+
if (node.knxAiCameraRefresh) node.knxAiCameraRefreshAgain = true;
|
|
775
|
+
}
|
|
530
776
|
},
|
|
531
777
|
handleProtectEventUpdate(update) {
|
|
532
778
|
const item = update && update.item;
|
|
533
779
|
if (!item || item.modelKey !== "event" || node.knxAiCameraListeners.size === 0) return;
|
|
534
|
-
|
|
780
|
+
const eventType = String(item.type || "").trim();
|
|
781
|
+
if (!SMART_CAMERA_EVENTS.has(eventType)) return;
|
|
782
|
+
Promise.resolve(node.listKnxAiCameras({ allowStale: true })).then((cameras) => {
|
|
535
783
|
const camera = cameras.find((entry) => entry.nativeCameraId === String(item.device || ""));
|
|
536
784
|
const event = normalizeProtectCameraEvent({
|
|
537
785
|
event: item,
|
|
@@ -549,6 +797,7 @@ module.exports = function(RED) {
|
|
|
549
797
|
}
|
|
550
798
|
};
|
|
551
799
|
|
|
800
|
+
const historyCapabilities = node.hasHistoryCredentials() ? ["event_history", "event_snapshot"] : [];
|
|
552
801
|
const knxAiProvider = {
|
|
553
802
|
id: `unifi-ultimate:${node.id}`,
|
|
554
803
|
adapterId: "unifi-ultimate",
|
|
@@ -556,7 +805,7 @@ module.exports = function(RED) {
|
|
|
556
805
|
packageName: "node-red-contrib-unifi-ultimate",
|
|
557
806
|
controllerId: node.id,
|
|
558
807
|
controllerName: node.name || node.host || node.id,
|
|
559
|
-
capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines"],
|
|
808
|
+
capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines"].concat(historyCapabilities),
|
|
560
809
|
listCameras: (options) => node.listKnxAiCameras(options),
|
|
561
810
|
takeSnapshot: (request) => node.takeKnxAiCameraSnapshot(request),
|
|
562
811
|
subscribe(listener) {
|
|
@@ -570,6 +819,10 @@ module.exports = function(RED) {
|
|
|
570
819
|
};
|
|
571
820
|
}
|
|
572
821
|
};
|
|
822
|
+
if (node.hasHistoryCredentials()) {
|
|
823
|
+
knxAiProvider.queryEvents = (request) => node.queryKnxAiCameraEvents(request);
|
|
824
|
+
knxAiProvider.takeEventSnapshot = (request) => node.takeKnxAiCameraEventSnapshot(request);
|
|
825
|
+
}
|
|
573
826
|
node.knxAiCameraProvider = knxAiProvider;
|
|
574
827
|
knxAiCameraRegistry.registerProvider(knxAiProvider);
|
|
575
828
|
|
|
@@ -578,6 +831,8 @@ module.exports = function(RED) {
|
|
|
578
831
|
node.isClosing = true;
|
|
579
832
|
knxAiCameraRegistry.unregisterProvider(knxAiProvider.id);
|
|
580
833
|
node.knxAiCameraListeners.clear();
|
|
834
|
+
node.protectHistorySessionHeaders = null;
|
|
835
|
+
node.protectHistoryPaginationGuard.clear();
|
|
581
836
|
node.removeClient(knxAiBridgeClient);
|
|
582
837
|
node.closeWebSockets();
|
|
583
838
|
} catch (error) {
|
|
@@ -591,7 +846,9 @@ module.exports = function(RED) {
|
|
|
591
846
|
|
|
592
847
|
RED.nodes.registerType("unifi-protect-config", UnifiProtectConfigNode, {
|
|
593
848
|
credentials: {
|
|
594
|
-
apiKey: { type: "password" }
|
|
849
|
+
apiKey: { type: "password" },
|
|
850
|
+
historyUsername: { type: "text" },
|
|
851
|
+
historyPassword: { type: "password" }
|
|
595
852
|
}
|
|
596
853
|
});
|
|
597
854
|
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { createHash } = require("crypto");
|
|
4
|
+
|
|
5
|
+
const {
|
|
6
|
+
SMART_CAMERA_EVENTS,
|
|
7
|
+
normalizeSearchText
|
|
8
|
+
} = require("./knx-ai-camera-registry");
|
|
9
|
+
|
|
10
|
+
const PROTECT_HISTORY_DEFAULT_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
11
|
+
const PROTECT_HISTORY_PAGE_SIZE = 100;
|
|
12
|
+
const PROTECT_HISTORY_MAX_RESULTS = 100;
|
|
13
|
+
const PROTECT_HISTORY_PAGINATION_TTL_MS = 5 * 60 * 1000;
|
|
14
|
+
const PROTECT_HISTORY_PAGINATION_MAX_QUERIES = 32;
|
|
15
|
+
|
|
16
|
+
function normalizeText(value, maxLength = 240) {
|
|
17
|
+
return String(value === undefined || value === null ? "" : value).trim().slice(0, maxLength);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function uniqueStrings(values, maxItems = 32) {
|
|
21
|
+
return Array.from(new Set((Array.isArray(values) ? values : [values])
|
|
22
|
+
.map((value) => normalizeText(value, 160))
|
|
23
|
+
.filter(Boolean)))
|
|
24
|
+
.slice(0, maxItems);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function normalizeHistoryEventType(value) {
|
|
28
|
+
const compact = normalizeSearchText(value).replace(/\s+/g, "");
|
|
29
|
+
if (["smartdetect", "smartdetection", "objectdetect", "objectdetection"].includes(compact)) return "smartDetect";
|
|
30
|
+
if (["smartdetectline", "line", "linecrossing", "crossline"].includes(compact)) return "smartDetectLine";
|
|
31
|
+
if (["smartdetectzone", "zone", "intrusion", "intrusionzone"].includes(compact)) return "smartDetectZone";
|
|
32
|
+
if (["smartdetectloiterzone", "loiter", "loiterzone"].includes(compact)) return "smartDetectLoiterZone";
|
|
33
|
+
if (["motion", "movement", "movimento"].includes(compact)) return "motion";
|
|
34
|
+
if (["ring", "doorbell"].includes(compact)) return "ring";
|
|
35
|
+
if (["smartaudiodetect", "audio"].includes(compact)) return "smartAudioDetect";
|
|
36
|
+
return normalizeText(value, 80);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function expandHistoryEventTypes(values) {
|
|
40
|
+
const requested = uniqueStrings(values).map(normalizeHistoryEventType).filter(Boolean);
|
|
41
|
+
const expanded = [];
|
|
42
|
+
requested.forEach((type) => {
|
|
43
|
+
if (type === "motion" || type === "smartDetect") {
|
|
44
|
+
expanded.push("motion", "smartDetectZone", "smartDetectLine", "smartDetectLoiterZone");
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (SMART_CAMERA_EVENTS.has(type)) expanded.push(type);
|
|
48
|
+
});
|
|
49
|
+
return Array.from(new Set(expanded));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function normalizeObjectTypes(values) {
|
|
53
|
+
return uniqueStrings(values, 12)
|
|
54
|
+
.map((value) => normalizeSearchText(value).replace(/\s+/g, ""))
|
|
55
|
+
.filter(Boolean);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function parseHistoryTime(value, fallback, label) {
|
|
59
|
+
const text = normalizeText(value, 80);
|
|
60
|
+
if (!text) return fallback;
|
|
61
|
+
const parsed = new Date(text).getTime();
|
|
62
|
+
if (!Number.isFinite(parsed)) throw new Error(`Invalid Protect history ${label} timestamp.`);
|
|
63
|
+
return parsed;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function normalizeProtectHistoryRequest(request = {}, { now = Date.now() } = {}) {
|
|
67
|
+
const source = request && typeof request === "object" && !Array.isArray(request) ? request : {};
|
|
68
|
+
const end = parseHistoryTime(source.to || source.end, Number(now) + 10000, "end");
|
|
69
|
+
const start = parseHistoryTime(source.from || source.start, end - PROTECT_HISTORY_DEFAULT_WINDOW_MS, "start");
|
|
70
|
+
if (start > end) throw new Error("Protect history start must not be after end.");
|
|
71
|
+
const limit = Math.max(1, Math.min(PROTECT_HISTORY_MAX_RESULTS, Math.floor(Number(source.limit) || 20)));
|
|
72
|
+
const offset = Math.max(0, Math.min(Number.MAX_SAFE_INTEGER, Math.floor(Number(source.offset) || 0)));
|
|
73
|
+
const requestedEventTypes = uniqueStrings(Array.isArray(source.eventTypes) ? source.eventTypes : [source.eventType]);
|
|
74
|
+
const expandedEventTypes = expandHistoryEventTypes(requestedEventTypes);
|
|
75
|
+
if (requestedEventTypes.length && !expandedEventTypes.length) {
|
|
76
|
+
throw new Error("Unsupported UniFi Protect historical event type.");
|
|
77
|
+
}
|
|
78
|
+
// Protect has controller versions with unreliable range pagination when
|
|
79
|
+
// the types parameter is omitted. Asking for every supported camera event
|
|
80
|
+
// keeps the result deterministic without widening the public contract.
|
|
81
|
+
const eventTypes = expandedEventTypes.length ? expandedEventTypes : Array.from(SMART_CAMERA_EVENTS);
|
|
82
|
+
const objectTypes = normalizeObjectTypes(Array.isArray(source.objectTypes) ? source.objectTypes : [source.objectType]);
|
|
83
|
+
return {
|
|
84
|
+
cameraId: normalizeText(source.cameraId, 200),
|
|
85
|
+
cameraName: normalizeText(source.cameraName, 240),
|
|
86
|
+
start,
|
|
87
|
+
end,
|
|
88
|
+
from: new Date(start).toISOString(),
|
|
89
|
+
to: new Date(end).toISOString(),
|
|
90
|
+
limit,
|
|
91
|
+
offset,
|
|
92
|
+
pageSize: PROTECT_HISTORY_PAGE_SIZE,
|
|
93
|
+
eventTypes,
|
|
94
|
+
objectTypes,
|
|
95
|
+
query: {
|
|
96
|
+
start,
|
|
97
|
+
end,
|
|
98
|
+
limit: PROTECT_HISTORY_PAGE_SIZE,
|
|
99
|
+
offset,
|
|
100
|
+
orderDirection: "DESC",
|
|
101
|
+
withoutDescriptions: "false",
|
|
102
|
+
...(eventTypes.length ? { types: eventTypes } : {}),
|
|
103
|
+
...(objectTypes.length ? { smartDetectTypes: objectTypes } : {})
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function getHeader(response, name) {
|
|
109
|
+
const headers = response && response.headers && typeof response.headers === "object" ? response.headers : {};
|
|
110
|
+
const wanted = String(name || "").toLowerCase();
|
|
111
|
+
const key = Object.keys(headers).find((candidate) => candidate.toLowerCase() === wanted);
|
|
112
|
+
return key ? headers[key] : undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function extractProtectHistorySessionHeaders(response) {
|
|
116
|
+
const rawCookies = getHeader(response, "set-cookie");
|
|
117
|
+
const cookieValues = (Array.isArray(rawCookies) ? rawCookies : [rawCookies])
|
|
118
|
+
.map((value) => normalizeText(value, 8192).split(";", 1)[0])
|
|
119
|
+
.filter((value) => /^[^=;\s]+=[^;]+$/.test(value));
|
|
120
|
+
if (!cookieValues.length) throw new Error("UniFi OS login did not return a session cookie.");
|
|
121
|
+
const csrf = normalizeText(getHeader(response, "x-csrf-token"), 4096);
|
|
122
|
+
return {
|
|
123
|
+
Cookie: cookieValues.join("; "),
|
|
124
|
+
...(csrf ? { "X-CSRF-Token": csrf } : {})
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function fingerprintProtectHistoryPage(events) {
|
|
129
|
+
if (!Array.isArray(events) || events.length === 0) return "";
|
|
130
|
+
const hash = createHash("sha256");
|
|
131
|
+
events.forEach((event) => {
|
|
132
|
+
if (!event || typeof event !== "object" || Array.isArray(event)) {
|
|
133
|
+
hash.update(JSON.stringify([normalizeText(event, 500)]));
|
|
134
|
+
} else {
|
|
135
|
+
hash.update(JSON.stringify([
|
|
136
|
+
normalizeText(event.id || event.eventId, 200),
|
|
137
|
+
normalizeText(event.device || event.camera || event.cameraId, 200),
|
|
138
|
+
normalizeText(event.type || event.eventType, 100),
|
|
139
|
+
normalizeText(event.start === undefined ? event.timestamp : event.start, 100),
|
|
140
|
+
normalizeText(event.end, 100),
|
|
141
|
+
normalizeText(event.thumbnail || event.thumbnailId, 200)
|
|
142
|
+
]));
|
|
143
|
+
}
|
|
144
|
+
hash.update("\n");
|
|
145
|
+
});
|
|
146
|
+
return hash.digest("hex");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function createProtectHistoryPaginationGuard({
|
|
150
|
+
ttlMs = PROTECT_HISTORY_PAGINATION_TTL_MS,
|
|
151
|
+
maxQueries = PROTECT_HISTORY_PAGINATION_MAX_QUERIES
|
|
152
|
+
} = {}) {
|
|
153
|
+
const states = new Map();
|
|
154
|
+
const normalizedTtl = Math.max(1000, Number(ttlMs) || PROTECT_HISTORY_PAGINATION_TTL_MS);
|
|
155
|
+
const normalizedMaxQueries = Math.max(1, Math.floor(Number(maxQueries) || PROTECT_HISTORY_PAGINATION_MAX_QUERIES));
|
|
156
|
+
|
|
157
|
+
function prune(now, currentKey) {
|
|
158
|
+
states.forEach((state, key) => {
|
|
159
|
+
if (key !== currentKey && now - state.updatedAt > normalizedTtl) states.delete(key);
|
|
160
|
+
});
|
|
161
|
+
while (!states.has(currentKey) && states.size >= normalizedMaxQueries) {
|
|
162
|
+
const oldest = Array.from(states.entries())
|
|
163
|
+
.sort((left, right) => left[1].updatedAt - right[1].updatedAt)[0];
|
|
164
|
+
if (!oldest) break;
|
|
165
|
+
states.delete(oldest[0]);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
evaluate({ key, offset = 0, pageSize = PROTECT_HISTORY_PAGE_SIZE, events, now = Date.now() } = {}) {
|
|
171
|
+
const queryKey = normalizeText(key, 4096) || "default";
|
|
172
|
+
const pageOffset = Math.max(0, Math.min(Number.MAX_SAFE_INTEGER, Math.floor(Number(offset) || 0)));
|
|
173
|
+
const normalizedPageSize = Math.max(1, Math.floor(Number(pageSize) || PROTECT_HISTORY_PAGE_SIZE));
|
|
174
|
+
const page = Array.isArray(events) ? events : [];
|
|
175
|
+
const signature = fingerprintProtectHistoryPage(page);
|
|
176
|
+
const checkedAt = Number.isFinite(Number(now)) ? Number(now) : Date.now();
|
|
177
|
+
prune(checkedAt, queryKey);
|
|
178
|
+
|
|
179
|
+
let state = states.get(queryKey);
|
|
180
|
+
if (!state || pageOffset === 0) {
|
|
181
|
+
state = { signatures: new Map(), updatedAt: checkedAt };
|
|
182
|
+
states.set(queryKey, state);
|
|
183
|
+
}
|
|
184
|
+
const previousOffset = signature ? state.signatures.get(signature) : undefined;
|
|
185
|
+
// Re-reading an explicit offset is legitimate. A controller returning
|
|
186
|
+
// a page already seen at a different offset is not: continuing from
|
|
187
|
+
// it would let callers paginate forever without new evidence.
|
|
188
|
+
const duplicatePage = pageOffset > 0
|
|
189
|
+
&& previousOffset !== undefined
|
|
190
|
+
&& previousOffset !== pageOffset;
|
|
191
|
+
if (signature) state.signatures.set(signature, pageOffset);
|
|
192
|
+
state.updatedAt = checkedAt;
|
|
193
|
+
|
|
194
|
+
const candidateOffset = pageOffset + page.length;
|
|
195
|
+
const madeProgress = page.length > 0
|
|
196
|
+
&& Number.isSafeInteger(candidateOffset)
|
|
197
|
+
&& candidateOffset > pageOffset
|
|
198
|
+
&& !duplicatePage;
|
|
199
|
+
const hasMore = page.length >= normalizedPageSize && madeProgress;
|
|
200
|
+
return {
|
|
201
|
+
duplicatePage,
|
|
202
|
+
duplicateOffset: duplicatePage ? previousOffset : null,
|
|
203
|
+
madeProgress,
|
|
204
|
+
hasMore,
|
|
205
|
+
nextOffset: hasMore ? candidateOffset : null,
|
|
206
|
+
signature
|
|
207
|
+
};
|
|
208
|
+
},
|
|
209
|
+
clear() {
|
|
210
|
+
states.clear();
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function selectProtectHistoryEvents(events, request) {
|
|
216
|
+
const normalized = normalizeProtectHistoryRequest(request, { now: request && request.end || Date.now() });
|
|
217
|
+
const wantedCameraId = normalizeText(normalized.cameraId, 200);
|
|
218
|
+
const wantedTypes = new Set(normalized.eventTypes);
|
|
219
|
+
const wantedObjects = new Set(normalized.objectTypes);
|
|
220
|
+
return (Array.isArray(events) ? events : [])
|
|
221
|
+
.filter((event) => {
|
|
222
|
+
if (!event || typeof event !== "object") return false;
|
|
223
|
+
if (wantedCameraId && normalizeText(event.cameraId || event.device, 200) !== wantedCameraId) return false;
|
|
224
|
+
if (wantedTypes.size && !wantedTypes.has(normalizeHistoryEventType(event.eventType || event.type))) return false;
|
|
225
|
+
if (wantedObjects.size) {
|
|
226
|
+
const detected = normalizeObjectTypes(event.objectTypes || event.smartDetectTypes || []);
|
|
227
|
+
if (!detected.some((type) => wantedObjects.has(type))) return false;
|
|
228
|
+
}
|
|
229
|
+
return true;
|
|
230
|
+
})
|
|
231
|
+
.sort((left, right) => new Date(right.at || right.start || 0).getTime() - new Date(left.at || left.start || 0).getTime())
|
|
232
|
+
.slice(0, normalized.limit);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
module.exports = {
|
|
236
|
+
PROTECT_HISTORY_DEFAULT_WINDOW_MS,
|
|
237
|
+
PROTECT_HISTORY_MAX_RESULTS,
|
|
238
|
+
PROTECT_HISTORY_PAGE_SIZE,
|
|
239
|
+
createProtectHistoryPaginationGuard,
|
|
240
|
+
expandHistoryEventTypes,
|
|
241
|
+
extractProtectHistorySessionHeaders,
|
|
242
|
+
fingerprintProtectHistoryPage,
|
|
243
|
+
normalizeProtectHistoryRequest,
|
|
244
|
+
selectProtectHistoryEvents
|
|
245
|
+
};
|
|
@@ -26,6 +26,14 @@ function buildBaseUrlFromHost(value, port) {
|
|
|
26
26
|
return `https://${host}/proxy/protect/integration`;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
function buildControllerBaseUrlFromHost(value, port) {
|
|
30
|
+
const host = applyPortToHost(normalizeHost(value), port);
|
|
31
|
+
if (!host) {
|
|
32
|
+
return "";
|
|
33
|
+
}
|
|
34
|
+
return `https://${host}`;
|
|
35
|
+
}
|
|
36
|
+
|
|
29
37
|
function buildQueryString(query) {
|
|
30
38
|
if (!query || typeof query !== "object" || Array.isArray(query)) {
|
|
31
39
|
return "";
|
|
@@ -134,6 +142,7 @@ function buildRequestBody(headers, method, payload) {
|
|
|
134
142
|
|
|
135
143
|
module.exports = {
|
|
136
144
|
buildBaseUrlFromHost,
|
|
145
|
+
buildControllerBaseUrlFromHost,
|
|
137
146
|
normalizePort,
|
|
138
147
|
applyPortToHost,
|
|
139
148
|
buildQueryString,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "node-red-contrib-unifi-ultimate",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.11",
|
|
4
4
|
"description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
|
|
5
5
|
"files": [
|
|
6
6
|
"nodes/",
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
}
|
|
67
67
|
},
|
|
68
68
|
"scripts": {
|
|
69
|
-
"test": "node --check nodes/unifi-access-config.js && node --check nodes/unifi-access-device.js && node --check nodes/unifi-network-config.js && node --check nodes/unifi-network-control-poe.js && node --check nodes/unifi-network-device.js && node --check nodes/unifi-network-presence.js && node --check nodes/unifi-network-restart.js && node --check nodes/unifi-protect-config.js && node --check nodes/unifi-protect-device.js && node --check nodes/utils/common-utils.js && node --check nodes/utils/http-response-utils.js && node --check nodes/utils/unifi-access-utils.js && node --check nodes/utils/unifi-access-device-registry.js && node --check nodes/utils/unifi-network-utils.js && node --check nodes/utils/unifi-network-device-registry.js && node --check nodes/utils/unifi-network-presence-utils.js && node --check nodes/utils/unifi-protect-utils.js && node --check nodes/utils/unifi-protect-field-metadata.js && node --check nodes/utils/unifi-protect-device-registry.js && node --check nodes/utils/knx-ai-camera-registry.js && node --check scripts/unifi-registry-discovery-common.js && node --check scripts/discover-unifi-network-registry.js && node --check scripts/discover-unifi-protect-registry.js && node --check scripts/discover-unifi-access-registry.js && jest",
|
|
69
|
+
"test": "node --check nodes/unifi-access-config.js && node --check nodes/unifi-access-device.js && node --check nodes/unifi-network-config.js && node --check nodes/unifi-network-control-poe.js && node --check nodes/unifi-network-device.js && node --check nodes/unifi-network-presence.js && node --check nodes/unifi-network-restart.js && node --check nodes/unifi-protect-config.js && node --check nodes/unifi-protect-device.js && node --check nodes/utils/common-utils.js && node --check nodes/utils/http-response-utils.js && node --check nodes/utils/unifi-access-utils.js && node --check nodes/utils/unifi-access-device-registry.js && node --check nodes/utils/unifi-network-utils.js && node --check nodes/utils/unifi-network-device-registry.js && node --check nodes/utils/unifi-network-presence-utils.js && node --check nodes/utils/unifi-protect-utils.js && node --check nodes/utils/unifi-protect-history.js && node --check nodes/utils/unifi-protect-field-metadata.js && node --check nodes/utils/unifi-protect-device-registry.js && node --check nodes/utils/knx-ai-camera-registry.js && node --check scripts/unifi-registry-discovery-common.js && node --check scripts/discover-unifi-network-registry.js && node --check scripts/discover-unifi-protect-registry.js && node --check scripts/discover-unifi-access-registry.js && jest",
|
|
70
70
|
"registry:discover:network": "node scripts/discover-unifi-network-registry.js",
|
|
71
71
|
"registry:discover:protect": "node scripts/discover-unifi-protect-registry.js",
|
|
72
72
|
"registry:discover:access": "node scripts/discover-unifi-access-registry.js"
|