node-red-contrib-unifi-ultimate 1.1.7 → 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 +12 -6
- package/nodes/unifi-protect-config.html +24 -2
- package/nodes/unifi-protect-config.js +314 -42
- package/nodes/unifi-protect-device.html +2 -1
- package/nodes/utils/unifi-protect-device-registry.js +104 -0
- package/nodes/utils/unifi-protect-history.js +245 -0
- package/nodes/utils/unifi-protect-utils.js +9 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -124,17 +124,23 @@ Things you can do:
|
|
|
124
124
|
- Switch a viewer to a different live feed.
|
|
125
125
|
- Monitor bridges, Link Stations, alarm hubs, key fobs, sirens, relays, and speakers.
|
|
126
126
|
- Play or stop a siren, control relay outputs, and test speaker or siren sound.
|
|
127
|
+
- Read and select Protect Arm Profiles, then arm or disarm the local Alarm Manager from the NVR control.
|
|
127
128
|
|
|
128
|
-
### Automatic KNX AI camera adapter
|
|
129
|
+
### Automatic Cerebrum / KNX AI camera adapter
|
|
129
130
|
|
|
130
|
-
|
|
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:
|
|
131
132
|
|
|
132
|
-
- send a current camera snapshot to
|
|
133
|
+
- send a current camera snapshot to the chat channel;
|
|
133
134
|
- describe a fresh snapshot with the configured vision-capable LLM;
|
|
134
|
-
-
|
|
135
|
-
- 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
|
+
|
|
136
143
|
|
|
137
|
-
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.
|
|
138
144
|
|
|
139
145
|
<br/>
|
|
140
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",
|
|
@@ -194,6 +282,20 @@ module.exports = function(RED) {
|
|
|
194
282
|
: [];
|
|
195
283
|
};
|
|
196
284
|
|
|
285
|
+
node.fetchArmProfiles = async () => {
|
|
286
|
+
const response = await node.apiRequest({
|
|
287
|
+
path: "/v1/arm-profiles",
|
|
288
|
+
method: "GET"
|
|
289
|
+
});
|
|
290
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
291
|
+
throw new Error(`Failed to load Protect arm profiles (${response.statusCode})`);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
return Array.isArray(response.payload)
|
|
295
|
+
? response.payload
|
|
296
|
+
: [];
|
|
297
|
+
};
|
|
298
|
+
|
|
197
299
|
node.fetchCapabilityOptions = async (deviceType, deviceId, capabilityId, capabilityConfig) => {
|
|
198
300
|
const selectedDevice = deviceId
|
|
199
301
|
? await node.fetchDeviceByTypeAndId(deviceType, deviceId)
|
|
@@ -205,7 +307,8 @@ module.exports = function(RED) {
|
|
|
205
307
|
capabilityConfig,
|
|
206
308
|
fetchDevice: node.fetchDeviceByTypeAndId,
|
|
207
309
|
fetchDevices: node.fetchDevices,
|
|
208
|
-
fetchAssetFiles: node.fetchAssetFiles
|
|
310
|
+
fetchAssetFiles: node.fetchAssetFiles,
|
|
311
|
+
fetchArmProfiles: node.fetchArmProfiles
|
|
209
312
|
});
|
|
210
313
|
};
|
|
211
314
|
|
|
@@ -217,45 +320,76 @@ module.exports = function(RED) {
|
|
|
217
320
|
return getCapabilitiesForType(deviceType, selectedDevice);
|
|
218
321
|
};
|
|
219
322
|
|
|
220
|
-
node.listKnxAiCameras = async ({ force = false } = {}) => {
|
|
323
|
+
node.listKnxAiCameras = async ({ force = false, allowStale = false } = {}) => {
|
|
221
324
|
const now = Date.now();
|
|
222
|
-
|
|
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) {
|
|
223
331
|
return node.knxAiCameraCache.cameras.slice();
|
|
224
332
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
camera && camera.
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
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();
|
|
259
393
|
};
|
|
260
394
|
|
|
261
395
|
node.resolveKnxAiCamera = async ({ cameraId, cameraName } = {}) => {
|
|
@@ -329,6 +463,130 @@ module.exports = function(RED) {
|
|
|
329
463
|
};
|
|
330
464
|
};
|
|
331
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
|
+
|
|
332
590
|
node.buildWebSocketUrl = (path) => {
|
|
333
591
|
// Reuse the configured HTTPS base URL and only swap protocol for the
|
|
334
592
|
// matching websocket scheme.
|
|
@@ -511,12 +769,17 @@ module.exports = function(RED) {
|
|
|
511
769
|
id: `knx-ai-camera-adapter:${node.id}`,
|
|
512
770
|
handleProtectDeviceUpdate(update) {
|
|
513
771
|
const item = update && update.item;
|
|
514
|
-
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
|
+
}
|
|
515
776
|
},
|
|
516
777
|
handleProtectEventUpdate(update) {
|
|
517
778
|
const item = update && update.item;
|
|
518
779
|
if (!item || item.modelKey !== "event" || node.knxAiCameraListeners.size === 0) return;
|
|
519
|
-
|
|
780
|
+
const eventType = String(item.type || "").trim();
|
|
781
|
+
if (!SMART_CAMERA_EVENTS.has(eventType)) return;
|
|
782
|
+
Promise.resolve(node.listKnxAiCameras({ allowStale: true })).then((cameras) => {
|
|
520
783
|
const camera = cameras.find((entry) => entry.nativeCameraId === String(item.device || ""));
|
|
521
784
|
const event = normalizeProtectCameraEvent({
|
|
522
785
|
event: item,
|
|
@@ -534,6 +797,7 @@ module.exports = function(RED) {
|
|
|
534
797
|
}
|
|
535
798
|
};
|
|
536
799
|
|
|
800
|
+
const historyCapabilities = node.hasHistoryCredentials() ? ["event_history", "event_snapshot"] : [];
|
|
537
801
|
const knxAiProvider = {
|
|
538
802
|
id: `unifi-ultimate:${node.id}`,
|
|
539
803
|
adapterId: "unifi-ultimate",
|
|
@@ -541,7 +805,7 @@ module.exports = function(RED) {
|
|
|
541
805
|
packageName: "node-red-contrib-unifi-ultimate",
|
|
542
806
|
controllerId: node.id,
|
|
543
807
|
controllerName: node.name || node.host || node.id,
|
|
544
|
-
capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines"],
|
|
808
|
+
capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines"].concat(historyCapabilities),
|
|
545
809
|
listCameras: (options) => node.listKnxAiCameras(options),
|
|
546
810
|
takeSnapshot: (request) => node.takeKnxAiCameraSnapshot(request),
|
|
547
811
|
subscribe(listener) {
|
|
@@ -555,6 +819,10 @@ module.exports = function(RED) {
|
|
|
555
819
|
};
|
|
556
820
|
}
|
|
557
821
|
};
|
|
822
|
+
if (node.hasHistoryCredentials()) {
|
|
823
|
+
knxAiProvider.queryEvents = (request) => node.queryKnxAiCameraEvents(request);
|
|
824
|
+
knxAiProvider.takeEventSnapshot = (request) => node.takeKnxAiCameraEventSnapshot(request);
|
|
825
|
+
}
|
|
558
826
|
node.knxAiCameraProvider = knxAiProvider;
|
|
559
827
|
knxAiCameraRegistry.registerProvider(knxAiProvider);
|
|
560
828
|
|
|
@@ -563,6 +831,8 @@ module.exports = function(RED) {
|
|
|
563
831
|
node.isClosing = true;
|
|
564
832
|
knxAiCameraRegistry.unregisterProvider(knxAiProvider.id);
|
|
565
833
|
node.knxAiCameraListeners.clear();
|
|
834
|
+
node.protectHistorySessionHeaders = null;
|
|
835
|
+
node.protectHistoryPaginationGuard.clear();
|
|
566
836
|
node.removeClient(knxAiBridgeClient);
|
|
567
837
|
node.closeWebSockets();
|
|
568
838
|
} catch (error) {
|
|
@@ -576,7 +846,9 @@ module.exports = function(RED) {
|
|
|
576
846
|
|
|
577
847
|
RED.nodes.registerType("unifi-protect-config", UnifiProtectConfigNode, {
|
|
578
848
|
credentials: {
|
|
579
|
-
apiKey: { type: "password" }
|
|
849
|
+
apiKey: { type: "password" },
|
|
850
|
+
historyUsername: { type: "text" },
|
|
851
|
+
historyPassword: { type: "password" }
|
|
580
852
|
}
|
|
581
853
|
});
|
|
582
854
|
|
|
@@ -1163,9 +1163,10 @@
|
|
|
1163
1163
|
<p><b>Control</b> chooses the Protect device category. <b>Device</b> chooses the specific item. Device selectors are searchable and open with the complete list before filtering. A saved selection that is temporarily unavailable is preserved instead of being cleared.</p>
|
|
1164
1164
|
<p><b>Action</b> only shows actions supported by the selected device.</p>
|
|
1165
1165
|
<p>Additional fields appear only when the selected action needs extra input. For example, events, PTZ presets, live views, or discovered properties.</p>
|
|
1166
|
-
<p>Action highlights: <code>Receive Events</code>, <code>Read Device State</code>, <code>Take Snapshot</code>, <code>Show Doorbell Message</code>, siren play/stop/test, relay output control, speaker sound test, and
|
|
1166
|
+
<p>Action highlights: <code>Receive Events</code>, <code>Read Device State</code>, <code>Take Snapshot</code>, <code>Show Doorbell Message</code>, siren play/stop/test, relay output control, speaker sound test, and application/alarm actions on <code>NVR</code>.</p>
|
|
1167
1167
|
<p>Protect resources include cameras, sensors, lights, chimes, viewers, live views, NVRs, bridges, Link Stations, alarm hubs, key fobs, relays, sirens, and speakers. The newer device families expose read state and events without the generic raw-update action.</p>
|
|
1168
1168
|
<p><code>Play Siren</code> uses a duration in seconds. <code>Control Relay Output</code> requires an explicit output and on/off state; auto-off applies only when turning an output on. Sound-test actions use a configured volume and never read control values from the incoming message.</p>
|
|
1169
|
+
<p>Protect alarm arming is application-wide, so its actions are available under <code>NVR</code>, not on an individual Alarm Hub. Use <code>Read Arm Profiles</code>, <code>Select Arm Profile</code>, <code>Arm Alarm</code>, and <code>Disarm Alarm</code>. These endpoints require Protect's local Alarm Manager.</p>
|
|
1169
1170
|
<p><code>Receive Events</code> performs an initial fetch and then subscribes to streams managed by the shared Protect config node. The config node keeps websocket channels and forwards matching updates to runtime nodes. In this mode, the input pin is hidden and listening starts automatically after deploy/restart.</p>
|
|
1170
1171
|
<p>For <code>Sensor</code>, <code>Camera</code>, and <code>Light</code> observables, <code>All</code> emits every event for the selected device. Choosing a specific observable normalizes the main output to a derived value and keeps the original context in <code>msg.details.raw</code>. Event observables emit <code>true/false</code>; sensor metrics such as <code>Temperature</code>, <code>Humidity</code>, <code>Light Level</code>, and <code>Battery Level</code> emit numeric values.</p>
|
|
1171
1172
|
<p><b>Emit periodically</b> repeats read-only actions at the selected interval and sends each result to the flow. It is hidden for <code>Receive Events</code> and write actions.</p>
|
|
@@ -567,6 +567,62 @@ const TYPE_CAPABILITIES = {
|
|
|
567
567
|
method: "GET",
|
|
568
568
|
path: "/v1/meta/info",
|
|
569
569
|
mode: "request"
|
|
570
|
+
},
|
|
571
|
+
{
|
|
572
|
+
id: "getArmProfiles",
|
|
573
|
+
label: "Read Arm Profiles",
|
|
574
|
+
description: "Fetch the arm profiles configured in Protect's local Alarm Manager.",
|
|
575
|
+
method: "GET",
|
|
576
|
+
path: "/v1/arm-profiles",
|
|
577
|
+
mode: "request"
|
|
578
|
+
},
|
|
579
|
+
{
|
|
580
|
+
id: "setCurrentArmProfile",
|
|
581
|
+
label: "Select Arm Profile",
|
|
582
|
+
description: "Select the arm profile Protect will use the next time the alarm is armed.",
|
|
583
|
+
method: "PATCH",
|
|
584
|
+
path: "/v1/arm-profiles/settings",
|
|
585
|
+
mode: "request",
|
|
586
|
+
ignoreInputPayload: true,
|
|
587
|
+
useConfiguredPayload: true,
|
|
588
|
+
editor: {
|
|
589
|
+
fields: [
|
|
590
|
+
{
|
|
591
|
+
id: "armProfileId",
|
|
592
|
+
label: "Arm profile",
|
|
593
|
+
type: "select",
|
|
594
|
+
placeholder: "Select an arm profile"
|
|
595
|
+
}
|
|
596
|
+
]
|
|
597
|
+
},
|
|
598
|
+
requestComposer: ({ capabilityConfig }) => {
|
|
599
|
+
const armProfileId = String(capabilityConfig.armProfileId || "").trim();
|
|
600
|
+
if (!armProfileId) {
|
|
601
|
+
throw new Error("Select an arm profile before using this action.");
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
return {
|
|
605
|
+
payload: { armProfileId }
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
},
|
|
609
|
+
{
|
|
610
|
+
id: "enableArmAlarm",
|
|
611
|
+
label: "Arm Alarm",
|
|
612
|
+
description: "Arm Protect using the currently selected arm profile.",
|
|
613
|
+
method: "POST",
|
|
614
|
+
path: "/v1/arm-profiles/enable",
|
|
615
|
+
mode: "request",
|
|
616
|
+
ignoreInputPayload: true
|
|
617
|
+
},
|
|
618
|
+
{
|
|
619
|
+
id: "disableArmAlarm",
|
|
620
|
+
label: "Disarm Alarm",
|
|
621
|
+
description: "Disarm Protect's local Alarm Manager.",
|
|
622
|
+
method: "POST",
|
|
623
|
+
path: "/v1/arm-profiles/disable",
|
|
624
|
+
mode: "request",
|
|
625
|
+
ignoreInputPayload: true
|
|
570
626
|
}
|
|
571
627
|
],
|
|
572
628
|
bridge: [],
|
|
@@ -907,6 +963,24 @@ async function getCapabilityOptions(deviceType, capabilityId, context) {
|
|
|
907
963
|
};
|
|
908
964
|
}
|
|
909
965
|
|
|
966
|
+
if (deviceType === "nvr" && capabilityId === "setCurrentArmProfile") {
|
|
967
|
+
const armProfiles = context && typeof context.fetchArmProfiles === "function"
|
|
968
|
+
? await context.fetchArmProfiles()
|
|
969
|
+
: [];
|
|
970
|
+
const currentArmProfileId = firstDefinedValue(context && context.device, [
|
|
971
|
+
"armMode.armProfileId"
|
|
972
|
+
]);
|
|
973
|
+
return {
|
|
974
|
+
capabilityId,
|
|
975
|
+
fields: [buildArmProfileField(
|
|
976
|
+
armProfiles,
|
|
977
|
+
capability.editor.fields[0],
|
|
978
|
+
context && context.capabilityConfig,
|
|
979
|
+
currentArmProfileId
|
|
980
|
+
)]
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
|
|
910
984
|
if (deviceType === "camera" && capabilityId === "setDoorbellMessage") {
|
|
911
985
|
return buildDoorbellMessageFields(context, capability);
|
|
912
986
|
}
|
|
@@ -1025,6 +1099,36 @@ function buildLiveviewOptions(liveviews, allowEmpty, emptyLabel) {
|
|
|
1025
1099
|
return options;
|
|
1026
1100
|
}
|
|
1027
1101
|
|
|
1102
|
+
function buildArmProfileField(armProfiles, baseField, capabilityConfig, currentArmProfileId) {
|
|
1103
|
+
const profiles = Array.isArray(armProfiles) ? armProfiles : [];
|
|
1104
|
+
const options = profiles.map((profile) => ({
|
|
1105
|
+
value: String(profile && profile.id ? profile.id : ""),
|
|
1106
|
+
label: String((profile && profile.name) || (profile && profile.id) || "Arm profile")
|
|
1107
|
+
})).filter((option) => option.value);
|
|
1108
|
+
const discoveredProfileCount = options.length;
|
|
1109
|
+
const configuredId = String(
|
|
1110
|
+
normalizeObject(capabilityConfig).armProfileId
|
|
1111
|
+
|| currentArmProfileId
|
|
1112
|
+
|| ""
|
|
1113
|
+
).trim();
|
|
1114
|
+
|
|
1115
|
+
if (configuredId && !options.some((option) => option.value === configuredId)) {
|
|
1116
|
+
options.push({
|
|
1117
|
+
value: configuredId,
|
|
1118
|
+
label: `${configuredId} (saved; currently unavailable)`
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
return {
|
|
1123
|
+
...baseField,
|
|
1124
|
+
options,
|
|
1125
|
+
defaultValue: configuredId,
|
|
1126
|
+
helpText: discoveredProfileCount > 0
|
|
1127
|
+
? "The selected profile is stored in Protect and will be used by Arm Alarm."
|
|
1128
|
+
: "No arm profiles were returned. Arm profiles require Protect's local Alarm Manager."
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1028
1132
|
function isCapabilitySupportedForDevice(deviceType, capability, device) {
|
|
1029
1133
|
// Protect exposes one broad family of camera APIs, but not every camera
|
|
1030
1134
|
// model supports every feature. Filter those actions in the editor.
|
|
@@ -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"
|