node-red-contrib-unifi-ultimate 1.1.9 → 1.1.12
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,17 +126,6 @@ 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
|
|
130
|
-
|
|
131
|
-
When `node-red-contrib-knx-ultimate` is installed, every configured **Unifi Protect Config** instance automatically publishes its cameras to the KNX AI chat runtime. No Protect Device node, selector, or intermediate wire is required. KNX AI can then:
|
|
132
|
-
|
|
133
|
-
- send a current camera snapshot to Telegram or RedBot;
|
|
134
|
-
- describe a fresh snapshot with the configured vision-capable LLM;
|
|
135
|
-
- create persistent chat notifications for unclassified motion or generic smart detections, as well as line crossings, intrusion zones, and loiter zones;
|
|
136
|
-
- filter smart events by the camera's supported classifications, including people, animals, vehicles, faces, license plates, and packages, and optionally by an exact line or zone exposed by Protect.
|
|
137
|
-
|
|
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
|
-
|
|
140
129
|
<br/>
|
|
141
130
|
<br/>
|
|
142
131
|
<p align="left">
|
|
@@ -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;
|
|
@@ -75,13 +83,102 @@ function createSnapshotError({ camera, response, retriedWithStandardQuality }) {
|
|
|
75
83
|
return error;
|
|
76
84
|
}
|
|
77
85
|
|
|
86
|
+
const PROTECT_CAMERA_EVENT_DEDUPE_TTL_MS = 60 * 60 * 1000;
|
|
87
|
+
const PROTECT_CAMERA_EVENT_DEDUPE_MAX_ENTRIES = 2048;
|
|
88
|
+
|
|
89
|
+
function cloneProviderMetadataWithoutRaw(value) {
|
|
90
|
+
if (Array.isArray(value)) return value.map(cloneProviderMetadataWithoutRaw);
|
|
91
|
+
if (!value || typeof value !== "object") return value;
|
|
92
|
+
const clone = {};
|
|
93
|
+
Object.entries(value).forEach(([key, nested]) => {
|
|
94
|
+
if (key === "raw") return;
|
|
95
|
+
clone[key] = cloneProviderMetadataWithoutRaw(nested);
|
|
96
|
+
});
|
|
97
|
+
return clone;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function sortedSemanticValues(values) {
|
|
101
|
+
return Array.from(new Set((Array.isArray(values) ? values : [])
|
|
102
|
+
.map((value) => String(value === undefined || value === null ? "" : value).trim())
|
|
103
|
+
.filter(Boolean)))
|
|
104
|
+
.sort();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function createProtectCameraEventDeduper({
|
|
108
|
+
ttlMs = PROTECT_CAMERA_EVENT_DEDUPE_TTL_MS,
|
|
109
|
+
maxEntries = PROTECT_CAMERA_EVENT_DEDUPE_MAX_ENTRIES
|
|
110
|
+
} = {}) {
|
|
111
|
+
const entries = new Map();
|
|
112
|
+
const normalizedTtl = Math.max(1000, Number(ttlMs) || PROTECT_CAMERA_EVENT_DEDUPE_TTL_MS);
|
|
113
|
+
const normalizedMaxEntries = Math.max(1, Math.floor(Number(maxEntries) || PROTECT_CAMERA_EVENT_DEDUPE_MAX_ENTRIES));
|
|
114
|
+
let lastPrunedAt = 0;
|
|
115
|
+
|
|
116
|
+
function prune(now, force = false) {
|
|
117
|
+
if (!force && entries.size < normalizedMaxEntries && now - lastPrunedAt < Math.min(normalizedTtl, 60000)) return;
|
|
118
|
+
entries.forEach((entry, key) => {
|
|
119
|
+
if (now - entry.seenAt > normalizedTtl) entries.delete(key);
|
|
120
|
+
});
|
|
121
|
+
lastPrunedAt = now;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
shouldForward(event, sourceEvent, now = Date.now()) {
|
|
126
|
+
if (!event || typeof event !== "object") return false;
|
|
127
|
+
const checkedAt = Number.isFinite(Number(now)) ? Number(now) : Date.now();
|
|
128
|
+
prune(checkedAt);
|
|
129
|
+
const eventId = String(event.eventId || "").trim();
|
|
130
|
+
const key = eventId
|
|
131
|
+
? `id:${eventId}`
|
|
132
|
+
: `fallback:${event.cameraId || event.nativeCameraId || ""}:${event.eventType || ""}:${event.at || ""}`;
|
|
133
|
+
const rawEnd = sourceEvent && sourceEvent.end !== undefined && sourceEvent.end !== null
|
|
134
|
+
? String(sourceEvent.end)
|
|
135
|
+
: null;
|
|
136
|
+
const fingerprint = JSON.stringify({
|
|
137
|
+
source: event.source || "",
|
|
138
|
+
controllerId: event.controllerId || "",
|
|
139
|
+
controllerName: event.controllerName || "",
|
|
140
|
+
cameraId: event.cameraId || "",
|
|
141
|
+
nativeCameraId: event.nativeCameraId || "",
|
|
142
|
+
cameraName: event.cameraName || "",
|
|
143
|
+
eventId,
|
|
144
|
+
eventType: event.eventType || "",
|
|
145
|
+
at: event.at || "",
|
|
146
|
+
active: event.active === true,
|
|
147
|
+
end: rawEnd,
|
|
148
|
+
scopeId: event.scopeId || "",
|
|
149
|
+
scopeName: event.scopeName || "",
|
|
150
|
+
scopeIds: sortedSemanticValues(event.scopeIds),
|
|
151
|
+
objectTypes: sortedSemanticValues(event.objectTypes)
|
|
152
|
+
});
|
|
153
|
+
const previous = entries.get(key);
|
|
154
|
+
const isDuplicate = previous
|
|
155
|
+
&& previous.fingerprint === fingerprint
|
|
156
|
+
&& checkedAt - previous.seenAt <= normalizedTtl;
|
|
157
|
+
|
|
158
|
+
// Refresh insertion order even for duplicates so a noisy active event
|
|
159
|
+
// remains suppressed until it has actually gone quiet for the TTL.
|
|
160
|
+
entries.delete(key);
|
|
161
|
+
entries.set(key, { fingerprint, seenAt: checkedAt });
|
|
162
|
+
if (entries.size > normalizedMaxEntries) {
|
|
163
|
+
const oldestKey = entries.keys().next().value;
|
|
164
|
+
if (oldestKey !== undefined) entries.delete(oldestKey);
|
|
165
|
+
}
|
|
166
|
+
return !isDuplicate;
|
|
167
|
+
},
|
|
168
|
+
clear() {
|
|
169
|
+
entries.clear();
|
|
170
|
+
lastPrunedAt = 0;
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
78
175
|
module.exports = function(RED) {
|
|
79
176
|
const knxAiCameraRegistry = getKnxAiCameraRegistry();
|
|
80
177
|
knxAiCameraRegistry.registerAdapter({
|
|
81
178
|
id: "unifi-ultimate",
|
|
82
179
|
title: "UniFi Ultimate / Protect",
|
|
83
180
|
packageName: "node-red-contrib-unifi-ultimate",
|
|
84
|
-
capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines"]
|
|
181
|
+
capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines", "event_history", "event_snapshot"]
|
|
85
182
|
});
|
|
86
183
|
|
|
87
184
|
function UnifiProtectConfigNode(config) {
|
|
@@ -92,6 +189,7 @@ module.exports = function(RED) {
|
|
|
92
189
|
node.host = String(config.host || "").trim();
|
|
93
190
|
node.port = normalizePort(config.port);
|
|
94
191
|
node.baseUrl = buildBaseUrlFromHost(node.host, node.port);
|
|
192
|
+
node.controllerBaseUrl = buildControllerBaseUrlFromHost(node.host, node.port);
|
|
95
193
|
// UniFi controllers almost always use self-signed certificates, so accept
|
|
96
194
|
// them unless the user explicitly opted into strict verification.
|
|
97
195
|
node.rejectUnauthorized = config.rejectUnauthorized === true || config.rejectUnauthorized === "true";
|
|
@@ -101,10 +199,90 @@ module.exports = function(RED) {
|
|
|
101
199
|
node.reconnectTimer = null;
|
|
102
200
|
node.isClosing = false;
|
|
103
201
|
node.knxAiCameraCache = { at: 0, cameras: [] };
|
|
202
|
+
node.knxAiCameraRefresh = null;
|
|
203
|
+
node.knxAiCameraRefreshAgain = false;
|
|
104
204
|
node.knxAiCameraListeners = new Set();
|
|
205
|
+
node.protectHistorySessionHeaders = null;
|
|
206
|
+
node.protectHistoryAuthentication = null;
|
|
207
|
+
node.protectHistoryPaginationGuard = createProtectHistoryPaginationGuard();
|
|
208
|
+
node.protectCameraEventDeduper = createProtectCameraEventDeduper();
|
|
105
209
|
|
|
106
210
|
node.getApiKey = () => node.credentials && node.credentials.apiKey;
|
|
107
211
|
|
|
212
|
+
node.getHistoryCredentials = () => ({
|
|
213
|
+
username: String(node.credentials && node.credentials.historyUsername || "").trim(),
|
|
214
|
+
password: String(node.credentials && node.credentials.historyPassword || "")
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
node.hasHistoryCredentials = () => {
|
|
218
|
+
const credentials = node.getHistoryCredentials();
|
|
219
|
+
return Boolean(credentials.username && credentials.password);
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
node.authenticateProtectHistory = async () => {
|
|
223
|
+
if (node.protectHistorySessionHeaders) return node.protectHistorySessionHeaders;
|
|
224
|
+
if (node.protectHistoryAuthentication) return node.protectHistoryAuthentication;
|
|
225
|
+
const authentication = Promise.resolve().then(async () => {
|
|
226
|
+
const credentials = node.getHistoryCredentials();
|
|
227
|
+
if (!credentials.username || !credentials.password) {
|
|
228
|
+
const error = new Error("UniFi Protect historical events require the optional local history username and password in the Protect config node.");
|
|
229
|
+
error.code = "UNIFI_PROTECT_HISTORY_CREDENTIALS_REQUIRED";
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
232
|
+
if (!node.controllerBaseUrl) throw new Error("The configured IP is empty or invalid.");
|
|
233
|
+
const headers = {
|
|
234
|
+
Accept: "application/json",
|
|
235
|
+
"Content-Type": "application/json"
|
|
236
|
+
};
|
|
237
|
+
const body = buildRequestBody(headers, "POST", {
|
|
238
|
+
username: credentials.username,
|
|
239
|
+
password: credentials.password,
|
|
240
|
+
rememberMe: false
|
|
241
|
+
});
|
|
242
|
+
const response = await doRequest(new URL(`${node.controllerBaseUrl}/api/auth/login`), {
|
|
243
|
+
method: "POST",
|
|
244
|
+
headers,
|
|
245
|
+
timeout: 15000,
|
|
246
|
+
rejectUnauthorized: node.rejectUnauthorized
|
|
247
|
+
}, body);
|
|
248
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
249
|
+
const detail = extractProtectErrorDetail(response);
|
|
250
|
+
const error = new Error(`UniFi OS login for Protect history failed (HTTP ${response.statusCode || "unknown"}${detail ? `: ${detail}` : ""}).`);
|
|
251
|
+
error.code = "UNIFI_PROTECT_HISTORY_LOGIN_FAILED";
|
|
252
|
+
error.statusCode = Number(response.statusCode) || 0;
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
node.protectHistorySessionHeaders = extractProtectHistorySessionHeaders(response);
|
|
256
|
+
return node.protectHistorySessionHeaders;
|
|
257
|
+
}).finally(() => {
|
|
258
|
+
if (node.protectHistoryAuthentication === authentication) node.protectHistoryAuthentication = null;
|
|
259
|
+
});
|
|
260
|
+
node.protectHistoryAuthentication = authentication;
|
|
261
|
+
return authentication;
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
node.executeProtectHistoryRequest = async ({ path, method = "GET", query, headers, payload, timeout = 20000 } = {}, retryAuthentication = true) => {
|
|
265
|
+
const sessionHeaders = await node.authenticateProtectHistory();
|
|
266
|
+
const normalizedPath = String(path || "").replace(/^\/+/, "");
|
|
267
|
+
const requestUrl = new URL(`${node.controllerBaseUrl}/proxy/protect/api/${normalizedPath}${buildQueryString(query)}`);
|
|
268
|
+
const requestMethod = String(method || "GET").toUpperCase();
|
|
269
|
+
const requestHeaders = Object.assign({ Accept: "application/json" }, sessionHeaders, headers || {});
|
|
270
|
+
const requestBody = buildRequestBody(requestHeaders, requestMethod, payload);
|
|
271
|
+
const response = await doRequest(requestUrl, {
|
|
272
|
+
method: requestMethod,
|
|
273
|
+
headers: requestHeaders,
|
|
274
|
+
timeout,
|
|
275
|
+
rejectUnauthorized: node.rejectUnauthorized
|
|
276
|
+
}, requestBody);
|
|
277
|
+
const refreshedCsrf = response && response.headers && response.headers["x-csrf-token"];
|
|
278
|
+
if (refreshedCsrf && node.protectHistorySessionHeaders) node.protectHistorySessionHeaders["X-CSRF-Token"] = String(refreshedCsrf);
|
|
279
|
+
if (Number(response && response.statusCode) === 401 && retryAuthentication) {
|
|
280
|
+
node.protectHistorySessionHeaders = null;
|
|
281
|
+
return node.executeProtectHistoryRequest({ path, method, query, headers, payload, timeout }, false);
|
|
282
|
+
}
|
|
283
|
+
return response;
|
|
284
|
+
};
|
|
285
|
+
|
|
108
286
|
node.apiRequest = async ({
|
|
109
287
|
path,
|
|
110
288
|
method = "GET",
|
|
@@ -232,45 +410,76 @@ module.exports = function(RED) {
|
|
|
232
410
|
return getCapabilitiesForType(deviceType, selectedDevice);
|
|
233
411
|
};
|
|
234
412
|
|
|
235
|
-
node.listKnxAiCameras = async ({ force = false } = {}) => {
|
|
413
|
+
node.listKnxAiCameras = async ({ force = false, allowStale = false } = {}) => {
|
|
236
414
|
const now = Date.now();
|
|
237
|
-
|
|
415
|
+
const cachedCameras = Array.isArray(node.knxAiCameraCache.cameras)
|
|
416
|
+
? node.knxAiCameraCache.cameras.slice()
|
|
417
|
+
: [];
|
|
418
|
+
const cacheIsFresh = node.knxAiCameraCache.at > 0
|
|
419
|
+
&& (now - node.knxAiCameraCache.at) < 30000;
|
|
420
|
+
if (!force && cacheIsFresh) {
|
|
238
421
|
return node.knxAiCameraCache.cameras.slice();
|
|
239
422
|
}
|
|
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
|
-
|
|
423
|
+
if (node.knxAiCameraRefresh) {
|
|
424
|
+
if (!force && allowStale && cachedCameras.length > 0) return cachedCameras;
|
|
425
|
+
return (await node.knxAiCameraRefresh).slice();
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
let refresh;
|
|
429
|
+
refresh = Promise.resolve().then(() => node.fetchDevices("camera")).then((devices) => {
|
|
430
|
+
const cameras = devices.map((camera) => {
|
|
431
|
+
const nativeCameraId = String(camera && camera.id || "").trim();
|
|
432
|
+
const cameraName = String(camera && (camera.name || camera.displayName) || nativeCameraId).trim();
|
|
433
|
+
const cameraState = String(camera && camera.state || "").trim().toUpperCase();
|
|
434
|
+
const objectTypes = Array.from(new Set([].concat(
|
|
435
|
+
camera && camera.smartDetectSettings && Array.isArray(camera.smartDetectSettings.objectTypes)
|
|
436
|
+
? camera.smartDetectSettings.objectTypes
|
|
437
|
+
: [],
|
|
438
|
+
camera && camera.featureFlags && Array.isArray(camera.featureFlags.smartDetectTypes)
|
|
439
|
+
? camera.featureFlags.smartDetectTypes
|
|
440
|
+
: []
|
|
441
|
+
).map((value) => String(value || "").trim()).filter(Boolean)));
|
|
442
|
+
return {
|
|
443
|
+
id: `${node.id}:${nativeCameraId}`,
|
|
444
|
+
cameraId: `${node.id}:${nativeCameraId}`,
|
|
445
|
+
nativeCameraId,
|
|
446
|
+
cameraName,
|
|
447
|
+
name: cameraName,
|
|
448
|
+
aliases: [cameraName, nativeCameraId].filter(Boolean),
|
|
449
|
+
controllerId: node.id,
|
|
450
|
+
controllerName: node.name || node.host || node.id,
|
|
451
|
+
adapterId: "unifi-ultimate",
|
|
452
|
+
adapterTitle: "UniFi Ultimate / Protect",
|
|
453
|
+
source: "unifi-ultimate",
|
|
454
|
+
state: cameraState,
|
|
455
|
+
online: cameraState ? cameraState === "CONNECTED" : null,
|
|
456
|
+
objectTypes,
|
|
457
|
+
lines: collectNamedScopes(camera, "line"),
|
|
458
|
+
zones: collectNamedScopes(camera, "zone"),
|
|
459
|
+
raw: camera
|
|
460
|
+
};
|
|
461
|
+
}).filter((camera) => camera.nativeCameraId);
|
|
462
|
+
node.knxAiCameraCache = { at: Date.now(), cameras };
|
|
463
|
+
return cameras;
|
|
464
|
+
}).finally(() => {
|
|
465
|
+
if (node.knxAiCameraRefresh !== refresh) return;
|
|
466
|
+
node.knxAiCameraRefresh = null;
|
|
467
|
+
if (!node.knxAiCameraRefreshAgain || node.isClosing) return;
|
|
468
|
+
node.knxAiCameraRefreshAgain = false;
|
|
469
|
+
node.knxAiCameraCache = { at: 0, cameras: node.knxAiCameraCache.cameras };
|
|
470
|
+
Promise.resolve(node.listKnxAiCameras({ force: true })).catch((error) => {
|
|
471
|
+
node.warn(`Unable to refresh the KNX AI camera catalog: ${error && error.message ? error.message : error}`);
|
|
472
|
+
});
|
|
473
|
+
});
|
|
474
|
+
node.knxAiCameraRefresh = refresh;
|
|
475
|
+
|
|
476
|
+
if (!force && allowStale && cachedCameras.length > 0) {
|
|
477
|
+
refresh.catch((error) => {
|
|
478
|
+
node.warn(`Unable to refresh the KNX AI camera catalog: ${error && error.message ? error.message : error}`);
|
|
479
|
+
});
|
|
480
|
+
return cachedCameras;
|
|
481
|
+
}
|
|
482
|
+
return (await refresh).slice();
|
|
274
483
|
};
|
|
275
484
|
|
|
276
485
|
node.resolveKnxAiCamera = async ({ cameraId, cameraName } = {}) => {
|
|
@@ -339,7 +548,131 @@ module.exports = function(RED) {
|
|
|
339
548
|
return {
|
|
340
549
|
data: response.payload,
|
|
341
550
|
mediaType,
|
|
342
|
-
camera,
|
|
551
|
+
camera: cloneProviderMetadataWithoutRaw(camera),
|
|
552
|
+
statusCode: response.statusCode
|
|
553
|
+
};
|
|
554
|
+
};
|
|
555
|
+
|
|
556
|
+
node.queryKnxAiCameraEvents = async (request = {}) => {
|
|
557
|
+
const normalized = normalizeProtectHistoryRequest(request);
|
|
558
|
+
const requestSource = request && typeof request === "object" && !Array.isArray(request) ? request : {};
|
|
559
|
+
const paginationKey = JSON.stringify({
|
|
560
|
+
cameraId: normalized.cameraId,
|
|
561
|
+
cameraName: normalized.cameraName,
|
|
562
|
+
start: requestSource.from !== undefined || requestSource.start !== undefined ? normalized.start : "default",
|
|
563
|
+
end: requestSource.to !== undefined || requestSource.end !== undefined ? normalized.end : "default",
|
|
564
|
+
eventTypes: normalized.eventTypes,
|
|
565
|
+
objectTypes: normalized.objectTypes
|
|
566
|
+
});
|
|
567
|
+
const requestedCamera = normalized.cameraId || normalized.cameraName
|
|
568
|
+
? await node.resolveKnxAiCamera({ cameraId: normalized.cameraId, cameraName: normalized.cameraName })
|
|
569
|
+
: null;
|
|
570
|
+
const response = await node.executeProtectHistoryRequest({
|
|
571
|
+
path: "events",
|
|
572
|
+
method: "GET",
|
|
573
|
+
query: normalized.query,
|
|
574
|
+
timeout: 25000
|
|
575
|
+
});
|
|
576
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
577
|
+
const detail = extractProtectErrorDetail(response);
|
|
578
|
+
throw new Error(`Unable to retrieve UniFi Protect historical events (HTTP ${response.statusCode || "unknown"}${detail ? `: ${detail}` : ""}).`);
|
|
579
|
+
}
|
|
580
|
+
const payload = Array.isArray(response.payload)
|
|
581
|
+
? response.payload
|
|
582
|
+
: response.payload && Array.isArray(response.payload.events)
|
|
583
|
+
? response.payload.events
|
|
584
|
+
: response.payload && Array.isArray(response.payload.data)
|
|
585
|
+
? response.payload.data
|
|
586
|
+
: [];
|
|
587
|
+
const cameras = await node.listKnxAiCameras();
|
|
588
|
+
const events = payload.map((item) => {
|
|
589
|
+
if (!item || typeof item !== "object") return null;
|
|
590
|
+
const nativeCameraId = String(item.device || item.camera || item.cameraId || "").trim();
|
|
591
|
+
const startValue = item.start === undefined || item.start === null ? item.timestamp : item.start;
|
|
592
|
+
const numericStart = Number(startValue);
|
|
593
|
+
const start = Number.isFinite(numericStart) ? numericStart : Date.parse(String(startValue || ""));
|
|
594
|
+
if (!nativeCameraId || !Number.isFinite(start)) return null;
|
|
595
|
+
const numericEnd = Number(item.end);
|
|
596
|
+
const parsedEnd = item.end === null || item.end === undefined
|
|
597
|
+
? null
|
|
598
|
+
: Number.isFinite(numericEnd)
|
|
599
|
+
? numericEnd
|
|
600
|
+
: Date.parse(String(item.end));
|
|
601
|
+
const camera = cameras.find((candidate) => candidate.nativeCameraId === nativeCameraId);
|
|
602
|
+
const event = normalizeProtectCameraEvent({
|
|
603
|
+
event: Object.assign({}, item, {
|
|
604
|
+
modelKey: "event",
|
|
605
|
+
type: item.type || item.eventType,
|
|
606
|
+
device: nativeCameraId,
|
|
607
|
+
start
|
|
608
|
+
}),
|
|
609
|
+
camera: camera && camera.raw,
|
|
610
|
+
controllerId: node.id,
|
|
611
|
+
controllerName: node.name || node.host || node.id
|
|
612
|
+
});
|
|
613
|
+
if (!event) return null;
|
|
614
|
+
return Object.assign({}, event, {
|
|
615
|
+
endAt: Number.isFinite(parsedEnd) ? new Date(parsedEnd).toISOString() : "",
|
|
616
|
+
score: Number.isFinite(Number(item.score)) ? Number(item.score) : null,
|
|
617
|
+
thumbnailAvailable: Boolean(item.thumbnail || item.thumbnailId)
|
|
618
|
+
});
|
|
619
|
+
}).filter(Boolean);
|
|
620
|
+
const selected = selectProtectHistoryEvents(events, Object.assign({}, normalized, {
|
|
621
|
+
cameraId: requestedCamera && requestedCamera.id || ""
|
|
622
|
+
}));
|
|
623
|
+
const continuation = node.protectHistoryPaginationGuard.evaluate({
|
|
624
|
+
key: paginationKey,
|
|
625
|
+
offset: normalized.offset,
|
|
626
|
+
pageSize: normalized.pageSize,
|
|
627
|
+
events: payload
|
|
628
|
+
});
|
|
629
|
+
return {
|
|
630
|
+
events: continuation.duplicatePage ? [] : selected.map(cloneProviderMetadataWithoutRaw),
|
|
631
|
+
from: normalized.from,
|
|
632
|
+
to: normalized.to,
|
|
633
|
+
offset: normalized.offset,
|
|
634
|
+
nextOffset: continuation.nextOffset,
|
|
635
|
+
hasMore: continuation.hasMore,
|
|
636
|
+
scannedEvents: payload.length,
|
|
637
|
+
duplicatePage: continuation.duplicatePage,
|
|
638
|
+
continuationStoppedReason: continuation.duplicatePage
|
|
639
|
+
? "duplicate_page"
|
|
640
|
+
: !continuation.madeProgress && payload.length >= normalized.pageSize
|
|
641
|
+
? "no_progress"
|
|
642
|
+
: ""
|
|
643
|
+
};
|
|
644
|
+
};
|
|
645
|
+
|
|
646
|
+
node.takeKnxAiCameraEventSnapshot = async ({ eventId } = {}) => {
|
|
647
|
+
const id = String(eventId || "").trim().replace(/^e-/, "");
|
|
648
|
+
if (!id || id.length > 200) throw new Error("A valid UniFi Protect event id is required.");
|
|
649
|
+
let response;
|
|
650
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
651
|
+
response = await node.executeProtectHistoryRequest({
|
|
652
|
+
path: `events/${encodeURIComponent(id)}/thumbnail`,
|
|
653
|
+
method: "GET",
|
|
654
|
+
headers: { Accept: "image/jpeg" },
|
|
655
|
+
timeout: 25000
|
|
656
|
+
});
|
|
657
|
+
if (response.statusCode !== 404 || attempt === 3) break;
|
|
658
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
659
|
+
}
|
|
660
|
+
if (!response || response.statusCode < 200 || response.statusCode >= 300) {
|
|
661
|
+
const detail = extractProtectErrorDetail(response);
|
|
662
|
+
throw new Error(`Unable to retrieve the UniFi Protect event snapshot (HTTP ${response && response.statusCode || "unknown"}${detail ? `: ${detail}` : ""}).`);
|
|
663
|
+
}
|
|
664
|
+
if (!Buffer.isBuffer(response.payload) || response.payload.length === 0) {
|
|
665
|
+
throw new Error("UniFi Protect returned an empty or invalid event snapshot.");
|
|
666
|
+
}
|
|
667
|
+
const contentTypeHeader = response.headers && response.headers["content-type"];
|
|
668
|
+
const mediaType = String(Array.isArray(contentTypeHeader) ? contentTypeHeader[0] : contentTypeHeader || "image/jpeg")
|
|
669
|
+
.split(";")[0]
|
|
670
|
+
.trim()
|
|
671
|
+
.toLowerCase();
|
|
672
|
+
return {
|
|
673
|
+
data: response.payload,
|
|
674
|
+
mediaType,
|
|
675
|
+
eventId: id,
|
|
343
676
|
statusCode: response.statusCode
|
|
344
677
|
};
|
|
345
678
|
};
|
|
@@ -526,12 +859,17 @@ module.exports = function(RED) {
|
|
|
526
859
|
id: `knx-ai-camera-adapter:${node.id}`,
|
|
527
860
|
handleProtectDeviceUpdate(update) {
|
|
528
861
|
const item = update && update.item;
|
|
529
|
-
if (item && item.modelKey === "camera")
|
|
862
|
+
if (item && item.modelKey === "camera") {
|
|
863
|
+
node.knxAiCameraCache = { at: 0, cameras: node.knxAiCameraCache.cameras };
|
|
864
|
+
if (node.knxAiCameraRefresh) node.knxAiCameraRefreshAgain = true;
|
|
865
|
+
}
|
|
530
866
|
},
|
|
531
867
|
handleProtectEventUpdate(update) {
|
|
532
868
|
const item = update && update.item;
|
|
533
869
|
if (!item || item.modelKey !== "event" || node.knxAiCameraListeners.size === 0) return;
|
|
534
|
-
|
|
870
|
+
const eventType = String(item.type || "").trim();
|
|
871
|
+
if (!SMART_CAMERA_EVENTS.has(eventType)) return;
|
|
872
|
+
Promise.resolve(node.listKnxAiCameras({ allowStale: true })).then((cameras) => {
|
|
535
873
|
const camera = cameras.find((entry) => entry.nativeCameraId === String(item.device || ""));
|
|
536
874
|
const event = normalizeProtectCameraEvent({
|
|
537
875
|
event: item,
|
|
@@ -540,8 +878,10 @@ module.exports = function(RED) {
|
|
|
540
878
|
controllerName: node.name || node.host || node.id
|
|
541
879
|
});
|
|
542
880
|
if (!event) return;
|
|
881
|
+
if (!node.protectCameraEventDeduper.shouldForward(event, item)) return;
|
|
882
|
+
const publicEvent = cloneProviderMetadataWithoutRaw(event);
|
|
543
883
|
node.knxAiCameraListeners.forEach((listener) => {
|
|
544
|
-
try { listener(
|
|
884
|
+
try { listener(publicEvent); } catch (error) { }
|
|
545
885
|
});
|
|
546
886
|
}).catch((error) => {
|
|
547
887
|
node.warn(`KNX AI camera event adapter failed: ${error && error.message ? error.message : error}`);
|
|
@@ -549,6 +889,7 @@ module.exports = function(RED) {
|
|
|
549
889
|
}
|
|
550
890
|
};
|
|
551
891
|
|
|
892
|
+
const historyCapabilities = node.hasHistoryCredentials() ? ["event_history", "event_snapshot"] : [];
|
|
552
893
|
const knxAiProvider = {
|
|
553
894
|
id: `unifi-ultimate:${node.id}`,
|
|
554
895
|
adapterId: "unifi-ultimate",
|
|
@@ -556,8 +897,9 @@ module.exports = function(RED) {
|
|
|
556
897
|
packageName: "node-red-contrib-unifi-ultimate",
|
|
557
898
|
controllerId: node.id,
|
|
558
899
|
controllerName: node.name || node.host || node.id,
|
|
559
|
-
|
|
560
|
-
|
|
900
|
+
eventRetention: "none",
|
|
901
|
+
capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines"].concat(historyCapabilities),
|
|
902
|
+
listCameras: async (options) => (await node.listKnxAiCameras(options)).map(cloneProviderMetadataWithoutRaw),
|
|
561
903
|
takeSnapshot: (request) => node.takeKnxAiCameraSnapshot(request),
|
|
562
904
|
subscribe(listener) {
|
|
563
905
|
if (typeof listener !== "function") return () => { };
|
|
@@ -570,6 +912,10 @@ module.exports = function(RED) {
|
|
|
570
912
|
};
|
|
571
913
|
}
|
|
572
914
|
};
|
|
915
|
+
if (node.hasHistoryCredentials()) {
|
|
916
|
+
knxAiProvider.queryEvents = (request) => node.queryKnxAiCameraEvents(request);
|
|
917
|
+
knxAiProvider.takeEventSnapshot = (request) => node.takeKnxAiCameraEventSnapshot(request);
|
|
918
|
+
}
|
|
573
919
|
node.knxAiCameraProvider = knxAiProvider;
|
|
574
920
|
knxAiCameraRegistry.registerProvider(knxAiProvider);
|
|
575
921
|
|
|
@@ -578,6 +924,9 @@ module.exports = function(RED) {
|
|
|
578
924
|
node.isClosing = true;
|
|
579
925
|
knxAiCameraRegistry.unregisterProvider(knxAiProvider.id);
|
|
580
926
|
node.knxAiCameraListeners.clear();
|
|
927
|
+
node.protectHistorySessionHeaders = null;
|
|
928
|
+
node.protectHistoryPaginationGuard.clear();
|
|
929
|
+
node.protectCameraEventDeduper.clear();
|
|
581
930
|
node.removeClient(knxAiBridgeClient);
|
|
582
931
|
node.closeWebSockets();
|
|
583
932
|
} catch (error) {
|
|
@@ -591,7 +940,9 @@ module.exports = function(RED) {
|
|
|
591
940
|
|
|
592
941
|
RED.nodes.registerType("unifi-protect-config", UnifiProtectConfigNode, {
|
|
593
942
|
credentials: {
|
|
594
|
-
apiKey: { type: "password" }
|
|
943
|
+
apiKey: { type: "password" },
|
|
944
|
+
historyUsername: { type: "text" },
|
|
945
|
+
historyPassword: { type: "password" }
|
|
595
946
|
}
|
|
596
947
|
});
|
|
597
948
|
|
|
@@ -26,8 +26,10 @@ function normalizeSearchText(value) {
|
|
|
26
26
|
// This is the vendor-neutral KNX AI camera adapter contract. Keep this registry
|
|
27
27
|
// shape aligned with KNX Ultimate: an adapter describes package capabilities,
|
|
28
28
|
// while each configured controller registers a provider implementing
|
|
29
|
-
// listCameras(), takeSnapshot(), and subscribe().
|
|
30
|
-
//
|
|
29
|
+
// listCameras(), takeSnapshot(), and subscribe(). Optional queryEvents() and
|
|
30
|
+
// takeEventSnapshot() expose recorded evidence on demand. Providers declaring
|
|
31
|
+
// eventRetention: "none" keep their live feed transient in consumers. The
|
|
32
|
+
// shared Symbol avoids any direct package dependency or flow wiring.
|
|
31
33
|
function getKnxAiCameraRegistry() {
|
|
32
34
|
const existing = globalThis[KNX_AI_CAMERA_REGISTRY_KEY];
|
|
33
35
|
if (existing && existing.version === 1 && existing.adapters instanceof Map && existing.providers instanceof Map) {
|
|
@@ -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.12",
|
|
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"
|