node-red-contrib-unifi-ultimate 0.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +140 -0
- package/examples/unifi-protect-info.json +87 -0
- package/nodes/icons/unifi-protect-icon.svg +5 -0
- package/nodes/unifi-protect-config.html +52 -0
- package/nodes/unifi-protect-config.js +382 -0
- package/nodes/unifi-protect-device.html +715 -0
- package/nodes/unifi-protect-device.js +316 -0
- package/nodes/utils/unifi-protect-device-registry.js +1541 -0
- package/nodes/utils/unifi-protect-utils.js +153 -0
- package/package.json +41 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Massimo Saccani
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# node-red-contrib-unifi-ultimate
|
|
2
|
+
|
|
3
|
+
Node-RED nodes for Ubiquiti UniFi integrations, starting with UniFi Protect.
|
|
4
|
+
|
|
5
|
+
Current release status: `0.1.0-beta.1`
|
|
6
|
+
|
|
7
|
+
## Included in this first version
|
|
8
|
+
|
|
9
|
+
- `Unifi Protect Device`: generic Protect object node with discovery of device types, instances, and supported capabilities
|
|
10
|
+
- `Unifi Protect Config`: shared configuration node for controller IP, API key header, API key, and TLS behavior
|
|
11
|
+
|
|
12
|
+
## Supported Protect device types
|
|
13
|
+
|
|
14
|
+
- `Camera`
|
|
15
|
+
- `Sensor`
|
|
16
|
+
- `Light`
|
|
17
|
+
- `Chime`
|
|
18
|
+
- `Viewer`
|
|
19
|
+
- `Live View`
|
|
20
|
+
- `NVR`
|
|
21
|
+
|
|
22
|
+
## Supported capabilities
|
|
23
|
+
|
|
24
|
+
Common capabilities:
|
|
25
|
+
|
|
26
|
+
- `Observe`
|
|
27
|
+
- `Get details`
|
|
28
|
+
- `Patch settings`
|
|
29
|
+
|
|
30
|
+
Camera-specific capabilities:
|
|
31
|
+
|
|
32
|
+
- `Get snapshot`
|
|
33
|
+
- `Get snapshot` with `High quality` option
|
|
34
|
+
- `Get RTSPS streams`
|
|
35
|
+
- `Create RTSPS streams`
|
|
36
|
+
- `Delete RTSPS streams`
|
|
37
|
+
- `Create talkback session`
|
|
38
|
+
- `Disable microphone permanently`
|
|
39
|
+
- `Start PTZ patrol`
|
|
40
|
+
- `Stop PTZ patrol`
|
|
41
|
+
- `Go to PTZ preset`
|
|
42
|
+
- `Set doorbell message`
|
|
43
|
+
- `Set property`
|
|
44
|
+
|
|
45
|
+
Patchable object capabilities:
|
|
46
|
+
|
|
47
|
+
- `Set property` for `Camera`, `Sensor`, `Light`, `Chime`, `Viewer`, and `Live View`
|
|
48
|
+
|
|
49
|
+
Viewer-specific capabilities:
|
|
50
|
+
|
|
51
|
+
- `Set live view`
|
|
52
|
+
|
|
53
|
+
## Configuration model
|
|
54
|
+
|
|
55
|
+
The config node asks only for the UniFi OS controller IP or `host[:port]`.
|
|
56
|
+
|
|
57
|
+
The package builds the Protect base URL automatically as:
|
|
58
|
+
|
|
59
|
+
- `https://<IP>/proxy/protect/integration`
|
|
60
|
+
|
|
61
|
+
The nodes append the operation path automatically, for example `/v1/meta/info`, `/v1/cameras`, or `/v1/sensors/:id`.
|
|
62
|
+
|
|
63
|
+
The API key header is configurable. The default is `X-API-Key`.
|
|
64
|
+
|
|
65
|
+
## Runtime behavior
|
|
66
|
+
|
|
67
|
+
The `Device` node supports runtime overrides via `msg`:
|
|
68
|
+
|
|
69
|
+
- `msg.deviceType`
|
|
70
|
+
- `msg.deviceId`
|
|
71
|
+
- `msg.capability`
|
|
72
|
+
- `msg.capabilityConfig`
|
|
73
|
+
- `msg.params`
|
|
74
|
+
- `msg.query`
|
|
75
|
+
- `msg.headers`
|
|
76
|
+
- `msg.payload`
|
|
77
|
+
|
|
78
|
+
Some capabilities expose options discovered from Protect and configured directly in the editor. For example:
|
|
79
|
+
|
|
80
|
+
- `Observe` on `Sensor` lets you choose which boolean observable to monitor
|
|
81
|
+
- `Observe` on `Camera` lets you choose boolean event-driven observables like ring, motion, and smart detections
|
|
82
|
+
- `Observe` on `Light` lets you choose boolean observables like motion or light on/off
|
|
83
|
+
- `Go to PTZ preset` can offer PTZ preset choices for the selected camera
|
|
84
|
+
- `Start PTZ patrol` offers patrol slot selection
|
|
85
|
+
- `Set doorbell message` guides predefined/custom/image doorbell messages and can load image assets from Protect
|
|
86
|
+
- `Set live view` can offer available live views for the selected viewer
|
|
87
|
+
- `Set property` discovers patchable properties from the selected device payload and adapts the value field to booleans, numbers, strings, or related object selections
|
|
88
|
+
|
|
89
|
+
In these cases, the node can be triggered by any input message and will build the correct request from the selected capability options.
|
|
90
|
+
|
|
91
|
+
For `Sensor + Observe`:
|
|
92
|
+
|
|
93
|
+
- `msg.payload` is normalized to `true` or `false`
|
|
94
|
+
- the full original device/event context is exposed in `msg.RAW`
|
|
95
|
+
|
|
96
|
+
The same boolean-output pattern now also applies to supported `Camera + Observe` and `Light + Observe` observables.
|
|
97
|
+
|
|
98
|
+
Output fields:
|
|
99
|
+
|
|
100
|
+
- Output 1: state or main capability response
|
|
101
|
+
- Output 2: Protect events for the selected device when capability is `Observe`
|
|
102
|
+
- `msg.unifiProtect`: standardized device metadata
|
|
103
|
+
- `msg.device`: last known object payload, when available
|
|
104
|
+
|
|
105
|
+
## Install locally
|
|
106
|
+
|
|
107
|
+
From your Node-RED user directory:
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
npm install /absolute/path/to/node-red-contrib-unifi-ultimate
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Then restart Node-RED.
|
|
114
|
+
|
|
115
|
+
## Official references used
|
|
116
|
+
|
|
117
|
+
- Node-RED Creating Nodes: https://nodered.org/docs/creating-nodes/
|
|
118
|
+
- Node-RED Config nodes: https://nodered.org/docs/creating-nodes/config-nodes
|
|
119
|
+
- Node-RED Credentials: https://nodered.org/docs/creating-nodes/credentials
|
|
120
|
+
- Node-RED Packaging: https://nodered.org/docs/creating-nodes/packaging.html
|
|
121
|
+
- UniFi Protect Getting Started: https://developer.ui.com/protect/v6.2.88/gettingstarted
|
|
122
|
+
- UniFi Protect Get Application Info: https://developer.ui.com/protect/v6.2.88/get-v1metainfo
|
|
123
|
+
- UniFi Protect Get Cameras: https://developer.ui.com/protect/v6.2.88/get-v1cameras
|
|
124
|
+
- UniFi Protect Get Camera Details: https://developer.ui.com/protect/v6.2.88/get-v1camerasid
|
|
125
|
+
- UniFi Protect Get Sensors: https://developer.ui.com/protect/v6.2.88/get-v1sensors
|
|
126
|
+
- UniFi Protect Get Lights: https://developer.ui.com/protect/v6.2.88/get-v1lights
|
|
127
|
+
- UniFi Protect Get Chimes: https://developer.ui.com/protect/v6.2.88/get-v1chimes
|
|
128
|
+
- UniFi Protect Get Viewers: https://developer.ui.com/protect/v6.2.88/get-v1viewers
|
|
129
|
+
- UniFi Protect Patch Viewer: https://developer.ui.com/protect/v6.2.88/patch-v1viewersid
|
|
130
|
+
- UniFi Protect Get Live Views: https://developer.ui.com/protect/v6.2.88/get-v1liveviews
|
|
131
|
+
- UniFi Protect Patch Live View: https://developer.ui.com/protect/v6.2.88/patch-v1liveviewsid
|
|
132
|
+
- UniFi Protect Get NVR Details: https://developer.ui.com/protect/v6.2.88/get-v1nvrs
|
|
133
|
+
- UniFi Protect Get Device Asset Files: https://developer.ui.com/protect/v6.2.88/get-v1filesfiletype
|
|
134
|
+
- UniFi Protect Upload Device Asset File: https://developer.ui.com/protect/v6.2.88/post-v1filesfiletype
|
|
135
|
+
- UniFi Protect Patch Sensor: https://developer.ui.com/protect/v6.2.88/patch-v1sensorsid
|
|
136
|
+
- UniFi Protect Patch Light: https://developer.ui.com/protect/v6.2.88/patch-v1lightsid
|
|
137
|
+
- UniFi Protect Patch Chime: https://developer.ui.com/protect/v6.2.88/patch-v1chimesid
|
|
138
|
+
- UniFi Protect Patch Camera: https://developer.ui.com/protect/v6.2.88/patch-v1camerasid
|
|
139
|
+
- UniFi Protect WebSocket Device Updates: https://developer.ui.com/protect/v6.2.88/get-v1subscribedevices
|
|
140
|
+
- UniFi Protect WebSocket Events: https://developer.ui.com/protect/v6.2.88/get-v1subscribeevents
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"id": "inject-unifi-protect-info",
|
|
4
|
+
"type": "inject",
|
|
5
|
+
"z": "flow-unifi-protect-example",
|
|
6
|
+
"name": "Observe Camera",
|
|
7
|
+
"props": [],
|
|
8
|
+
"repeat": "",
|
|
9
|
+
"crontab": "",
|
|
10
|
+
"once": false,
|
|
11
|
+
"onceDelay": 0.1,
|
|
12
|
+
"topic": "",
|
|
13
|
+
"x": 180,
|
|
14
|
+
"y": 120,
|
|
15
|
+
"wires": [
|
|
16
|
+
[
|
|
17
|
+
"node-unifi-protect-info"
|
|
18
|
+
]
|
|
19
|
+
]
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"id": "node-unifi-protect-info",
|
|
23
|
+
"type": "unifi-protect-device",
|
|
24
|
+
"z": "flow-unifi-protect-example",
|
|
25
|
+
"name": "Front Door Camera",
|
|
26
|
+
"server": "config-unifi-protect",
|
|
27
|
+
"deviceType": "camera",
|
|
28
|
+
"deviceId": "camera-id-here",
|
|
29
|
+
"capability": "observe",
|
|
30
|
+
"timeout": "15000",
|
|
31
|
+
"x": 430,
|
|
32
|
+
"y": 120,
|
|
33
|
+
"wires": [
|
|
34
|
+
[
|
|
35
|
+
"debug-unifi-protect-state"
|
|
36
|
+
],
|
|
37
|
+
[
|
|
38
|
+
"debug-unifi-protect-events"
|
|
39
|
+
]
|
|
40
|
+
]
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"id": "debug-unifi-protect-state",
|
|
44
|
+
"type": "debug",
|
|
45
|
+
"z": "flow-unifi-protect-example",
|
|
46
|
+
"name": "Device State",
|
|
47
|
+
"active": true,
|
|
48
|
+
"tosidebar": true,
|
|
49
|
+
"console": false,
|
|
50
|
+
"tostatus": false,
|
|
51
|
+
"complete": "true",
|
|
52
|
+
"targetType": "full",
|
|
53
|
+
"x": 710,
|
|
54
|
+
"y": 100,
|
|
55
|
+
"wires": []
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"id": "debug-unifi-protect-events",
|
|
59
|
+
"type": "debug",
|
|
60
|
+
"z": "flow-unifi-protect-example",
|
|
61
|
+
"name": "Device Events",
|
|
62
|
+
"active": true,
|
|
63
|
+
"tosidebar": true,
|
|
64
|
+
"console": false,
|
|
65
|
+
"tostatus": false,
|
|
66
|
+
"complete": "true",
|
|
67
|
+
"targetType": "full",
|
|
68
|
+
"x": 710,
|
|
69
|
+
"y": 140,
|
|
70
|
+
"wires": []
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"id": "config-unifi-protect",
|
|
74
|
+
"type": "unifi-protect-config",
|
|
75
|
+
"name": "My Protect",
|
|
76
|
+
"host": "192.168.1.10",
|
|
77
|
+
"authHeader": "X-API-Key",
|
|
78
|
+
"rejectUnauthorized": true
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
"id": "flow-unifi-protect-example",
|
|
82
|
+
"type": "tab",
|
|
83
|
+
"label": "UniFi Protect Device",
|
|
84
|
+
"disabled": false,
|
|
85
|
+
"info": ""
|
|
86
|
+
}
|
|
87
|
+
]
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
|
2
|
+
<rect x="8" y="12" width="48" height="40" rx="8" fill="#7DB7E8"/>
|
|
3
|
+
<path d="M32 22c-7.732 0-14 6.268-14 14s6.268 14 14 14 14-6.268 14-14-6.268-14-14-14zm0 6a8 8 0 1 1 0 16 8 8 0 0 1 0-16z" fill="#ffffff"/>
|
|
4
|
+
<circle cx="32" cy="36" r="3.5" fill="#0559C9"/>
|
|
5
|
+
</svg>
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
<script type="text/javascript">
|
|
2
|
+
RED.nodes.registerType("unifi-protect-config", {
|
|
3
|
+
category: "config",
|
|
4
|
+
defaults: {
|
|
5
|
+
name: { value: "Unifi Protect Config" },
|
|
6
|
+
host: { value: "", required: true },
|
|
7
|
+
authHeader: { value: "X-API-Key", required: true },
|
|
8
|
+
rejectUnauthorized: { value: false }
|
|
9
|
+
},
|
|
10
|
+
credentials: {
|
|
11
|
+
apiKey: { type: "password", required: true }
|
|
12
|
+
},
|
|
13
|
+
label: function () {
|
|
14
|
+
return this.name || this.host || "Unifi Protect Config";
|
|
15
|
+
},
|
|
16
|
+
oneditprepare: function () {
|
|
17
|
+
try {
|
|
18
|
+
RED.sidebar.show("help");
|
|
19
|
+
} catch (error) {
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
</script>
|
|
24
|
+
|
|
25
|
+
<script type="text/html" data-template-name="unifi-protect-config">
|
|
26
|
+
<div class="form-row">
|
|
27
|
+
<label for="node-config-input-name"><i class="fa fa-tag"></i> Name</label>
|
|
28
|
+
<input type="text" id="node-config-input-name" placeholder="Unifi Protect Config">
|
|
29
|
+
</div>
|
|
30
|
+
<div class="form-row">
|
|
31
|
+
<label for="node-config-input-host"><i class="fa fa-globe"></i> IP</label>
|
|
32
|
+
<input type="text" id="node-config-input-host" placeholder="192.168.1.10">
|
|
33
|
+
</div>
|
|
34
|
+
<div class="form-row">
|
|
35
|
+
<label for="node-config-input-authHeader"><i class="fa fa-header"></i> Auth Header</label>
|
|
36
|
+
<input type="text" id="node-config-input-authHeader" placeholder="X-API-Key">
|
|
37
|
+
</div>
|
|
38
|
+
<div class="form-row">
|
|
39
|
+
<label for="node-config-input-apiKey"><i class="fa fa-key"></i> API Key</label>
|
|
40
|
+
<input type="password" id="node-config-input-apiKey">
|
|
41
|
+
</div>
|
|
42
|
+
<div class="form-row">
|
|
43
|
+
<label for="node-config-input-rejectUnauthorized"><i class="fa fa-lock"></i> Verify TLS</label>
|
|
44
|
+
<input type="checkbox" id="node-config-input-rejectUnauthorized" style="display:inline-block; width:auto; vertical-align:top;">
|
|
45
|
+
<span style="margin-left:8px;">Reject invalid/self-signed certificates</span>
|
|
46
|
+
</div>
|
|
47
|
+
</script>
|
|
48
|
+
|
|
49
|
+
<script type="text/html" data-help-name="unifi-protect-config">
|
|
50
|
+
<p>Configurazione condivisa per i nodi UniFi Protect.</p>
|
|
51
|
+
<p>Inserisci l'<code>IP</code> o l'host del controller UniFi OS. Il nodo costruisce automaticamente il base URL Protect come <code>https://IP/proxy/protect/integration</code>.</p>
|
|
52
|
+
</script>
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const {
|
|
4
|
+
buildBaseUrlFromHost,
|
|
5
|
+
buildQueryString,
|
|
6
|
+
doRequest,
|
|
7
|
+
buildRequestHeaders,
|
|
8
|
+
buildRequestBody
|
|
9
|
+
} = require("./utils/unifi-protect-utils");
|
|
10
|
+
const {
|
|
11
|
+
getDeviceTypes,
|
|
12
|
+
getDeviceTypeDefinition,
|
|
13
|
+
getCapabilitiesForType,
|
|
14
|
+
getCapabilityOptions,
|
|
15
|
+
buildDevicePath,
|
|
16
|
+
normalizeDeviceCollection,
|
|
17
|
+
summarizeDevice
|
|
18
|
+
} = require("./utils/unifi-protect-device-registry");
|
|
19
|
+
|
|
20
|
+
module.exports = function(RED) {
|
|
21
|
+
function UnifiProtectConfigNode(config) {
|
|
22
|
+
RED.nodes.createNode(this, config);
|
|
23
|
+
|
|
24
|
+
const node = this;
|
|
25
|
+
node.name = config.name;
|
|
26
|
+
node.host = String(config.host || "").trim();
|
|
27
|
+
node.baseUrl = buildBaseUrlFromHost(node.host);
|
|
28
|
+
node.authHeader = (config.authHeader || "X-API-Key").trim() || "X-API-Key";
|
|
29
|
+
node.rejectUnauthorized = config.rejectUnauthorized !== false && config.rejectUnauthorized !== "false";
|
|
30
|
+
node.nodeClients = [];
|
|
31
|
+
node.wsDevices = null;
|
|
32
|
+
node.wsEvents = null;
|
|
33
|
+
node.reconnectTimer = null;
|
|
34
|
+
node.isClosing = false;
|
|
35
|
+
|
|
36
|
+
node.getApiKey = () => node.credentials && node.credentials.apiKey;
|
|
37
|
+
|
|
38
|
+
node.apiRequest = async ({
|
|
39
|
+
path,
|
|
40
|
+
method = "GET",
|
|
41
|
+
query,
|
|
42
|
+
headers,
|
|
43
|
+
payload,
|
|
44
|
+
timeout = 15000
|
|
45
|
+
}) => {
|
|
46
|
+
if (!node.baseUrl) {
|
|
47
|
+
throw new Error("The configured IP is empty or invalid.");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const apiKey = node.getApiKey();
|
|
51
|
+
if (!apiKey) {
|
|
52
|
+
throw new Error("The UniFi Protect API key is missing.");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const queryString = buildQueryString(query);
|
|
56
|
+
const normalizedPath = String(path || "").startsWith("/") ? String(path || "") : `/${String(path || "")}`;
|
|
57
|
+
const requestUrl = new URL(`${node.baseUrl}${normalizedPath}${queryString}`);
|
|
58
|
+
const requestMethod = String(method || "GET").toUpperCase();
|
|
59
|
+
const requestHeaders = buildRequestHeaders(node.authHeader, apiKey, headers);
|
|
60
|
+
const requestBody = buildRequestBody(requestHeaders, requestMethod, payload);
|
|
61
|
+
|
|
62
|
+
return doRequest(
|
|
63
|
+
requestUrl,
|
|
64
|
+
{
|
|
65
|
+
method: requestMethod,
|
|
66
|
+
headers: requestHeaders,
|
|
67
|
+
timeout,
|
|
68
|
+
rejectUnauthorized: node.rejectUnauthorized
|
|
69
|
+
},
|
|
70
|
+
requestBody
|
|
71
|
+
);
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
node.fetchDevices = async (deviceType) => {
|
|
75
|
+
const definition = getDeviceTypeDefinition(deviceType);
|
|
76
|
+
if (!definition) {
|
|
77
|
+
throw new Error(`Unsupported device type: ${deviceType}`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const response = await node.apiRequest({ path: definition.listPath, method: "GET" });
|
|
81
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
82
|
+
throw new Error(`Failed to load ${deviceType} devices (${response.statusCode})`);
|
|
83
|
+
}
|
|
84
|
+
return normalizeDeviceCollection(deviceType, response.payload);
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
node.fetchDeviceByTypeAndId = async (deviceType, deviceId) => {
|
|
88
|
+
const path = buildDevicePath(deviceType, "detail", deviceId);
|
|
89
|
+
const response = await node.apiRequest({
|
|
90
|
+
path,
|
|
91
|
+
method: "GET"
|
|
92
|
+
});
|
|
93
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
94
|
+
throw new Error(`Failed to load ${deviceType} ${deviceId || ""} (${response.statusCode})`);
|
|
95
|
+
}
|
|
96
|
+
return response.payload;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
node.fetchAssetFiles = async (fileType) => {
|
|
100
|
+
const normalizedType = String(fileType || "").trim();
|
|
101
|
+
if (!normalizedType) {
|
|
102
|
+
throw new Error("Missing file type.");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const response = await node.apiRequest({
|
|
106
|
+
path: `/v1/files/${encodeURIComponent(normalizedType)}`,
|
|
107
|
+
method: "GET"
|
|
108
|
+
});
|
|
109
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
110
|
+
throw new Error(`Failed to load files for ${normalizedType} (${response.statusCode})`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return Array.isArray(response.payload)
|
|
114
|
+
? response.payload
|
|
115
|
+
: [];
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
node.fetchCapabilityOptions = async (deviceType, deviceId, capabilityId, capabilityConfig) => {
|
|
119
|
+
return getCapabilityOptions(deviceType, capabilityId, {
|
|
120
|
+
deviceId,
|
|
121
|
+
capabilityConfig,
|
|
122
|
+
fetchDevice: node.fetchDeviceByTypeAndId,
|
|
123
|
+
fetchDevices: node.fetchDevices,
|
|
124
|
+
fetchAssetFiles: node.fetchAssetFiles
|
|
125
|
+
});
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
node.buildWebSocketUrl = (path) => {
|
|
129
|
+
const url = new URL(`${node.baseUrl}${path}`);
|
|
130
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
131
|
+
return url.toString();
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
node.broadcastDeviceUpdate = (update) => {
|
|
135
|
+
node.nodeClients.forEach((client) => {
|
|
136
|
+
try {
|
|
137
|
+
if (client && typeof client.handleProtectDeviceUpdate === "function") {
|
|
138
|
+
client.handleProtectDeviceUpdate(update);
|
|
139
|
+
}
|
|
140
|
+
} catch (error) {
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
node.broadcastEventUpdate = (update) => {
|
|
146
|
+
node.nodeClients.forEach((client) => {
|
|
147
|
+
try {
|
|
148
|
+
if (client && typeof client.handleProtectEventUpdate === "function") {
|
|
149
|
+
client.handleProtectEventUpdate(update);
|
|
150
|
+
}
|
|
151
|
+
} catch (error) {
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
node.scheduleReconnect = () => {
|
|
157
|
+
if (node.isClosing || node.reconnectTimer || node.nodeClients.length === 0) {
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
node.reconnectTimer = setTimeout(() => {
|
|
162
|
+
node.reconnectTimer = null;
|
|
163
|
+
node.ensureWebSockets();
|
|
164
|
+
}, 5000);
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
node.attachSocket = (kind, path, handler) => {
|
|
168
|
+
let WebSocket;
|
|
169
|
+
const apiKey = node.getApiKey();
|
|
170
|
+
if (!apiKey || !node.baseUrl) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
({ WebSocket } = require("ws"));
|
|
176
|
+
} catch (error) {
|
|
177
|
+
node.warn("The 'ws' dependency is not installed. UniFi Protect event streams are disabled until dependencies are installed.");
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const ws = new WebSocket(node.buildWebSocketUrl(path), {
|
|
182
|
+
headers: {
|
|
183
|
+
[node.authHeader]: apiKey,
|
|
184
|
+
Accept: "application/json"
|
|
185
|
+
},
|
|
186
|
+
rejectUnauthorized: node.rejectUnauthorized
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
ws.on("message", (rawData) => {
|
|
190
|
+
try {
|
|
191
|
+
const text = Buffer.isBuffer(rawData) ? rawData.toString("utf8") : String(rawData);
|
|
192
|
+
const parsed = JSON.parse(text);
|
|
193
|
+
handler(parsed);
|
|
194
|
+
} catch (error) {
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
ws.on("close", () => {
|
|
199
|
+
if (kind === "devices" && node.wsDevices === ws) {
|
|
200
|
+
node.wsDevices = null;
|
|
201
|
+
}
|
|
202
|
+
if (kind === "events" && node.wsEvents === ws) {
|
|
203
|
+
node.wsEvents = null;
|
|
204
|
+
}
|
|
205
|
+
node.scheduleReconnect();
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
ws.on("error", () => {
|
|
209
|
+
try {
|
|
210
|
+
ws.close();
|
|
211
|
+
} catch (error) {
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
if (kind === "devices") {
|
|
216
|
+
node.wsDevices = ws;
|
|
217
|
+
} else {
|
|
218
|
+
node.wsEvents = ws;
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
node.ensureWebSockets = () => {
|
|
223
|
+
if (node.isClosing || node.nodeClients.length === 0) {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (!node.wsDevices) {
|
|
228
|
+
node.attachSocket("devices", "/v1/subscribe/devices", node.broadcastDeviceUpdate);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (!node.wsEvents) {
|
|
232
|
+
node.attachSocket("events", "/v1/subscribe/events", node.broadcastEventUpdate);
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
node.closeWebSockets = () => {
|
|
237
|
+
if (node.reconnectTimer) {
|
|
238
|
+
clearTimeout(node.reconnectTimer);
|
|
239
|
+
node.reconnectTimer = null;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (node.wsDevices) {
|
|
243
|
+
try {
|
|
244
|
+
node.wsDevices.close();
|
|
245
|
+
} catch (error) {
|
|
246
|
+
}
|
|
247
|
+
node.wsDevices = null;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (node.wsEvents) {
|
|
251
|
+
try {
|
|
252
|
+
node.wsEvents.close();
|
|
253
|
+
} catch (error) {
|
|
254
|
+
}
|
|
255
|
+
node.wsEvents = null;
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
node.addClient = (client) => {
|
|
260
|
+
if (!client) {
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
node.nodeClients = node.nodeClients.filter((entry) => entry && entry.id !== client.id);
|
|
264
|
+
node.nodeClients.push(client);
|
|
265
|
+
node.ensureWebSockets();
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
node.removeClient = (client) => {
|
|
269
|
+
node.nodeClients = node.nodeClients.filter((entry) => entry && client && entry.id !== client.id);
|
|
270
|
+
if (node.nodeClients.length === 0) {
|
|
271
|
+
node.closeWebSockets();
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
node.on("close", function(done) {
|
|
276
|
+
node.isClosing = true;
|
|
277
|
+
node.closeWebSockets();
|
|
278
|
+
done();
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
RED.nodes.registerType("unifi-protect-config", UnifiProtectConfigNode, {
|
|
283
|
+
credentials: {
|
|
284
|
+
apiKey: { type: "password" }
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
RED.httpAdmin.get("/unifiProtect/device-types", RED.auth.needsPermission("unifi-protect-config.read"), async (req, res) => {
|
|
289
|
+
try {
|
|
290
|
+
res.json(getDeviceTypes().map((definition) => ({
|
|
291
|
+
type: definition.type,
|
|
292
|
+
label: definition.label,
|
|
293
|
+
modelKey: definition.modelKey
|
|
294
|
+
})));
|
|
295
|
+
} catch (error) {
|
|
296
|
+
res.status(500).json({ error: error.message });
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
RED.httpAdmin.get("/unifiProtect/device-capabilities", RED.auth.needsPermission("unifi-protect-config.read"), async (req, res) => {
|
|
301
|
+
try {
|
|
302
|
+
const deviceType = String(req.query.deviceType || "").trim();
|
|
303
|
+
if (!deviceType) {
|
|
304
|
+
res.status(400).json({ error: "Missing deviceType" });
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
res.json(getCapabilitiesForType(deviceType));
|
|
309
|
+
} catch (error) {
|
|
310
|
+
res.status(500).json({ error: error.message });
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
RED.httpAdmin.get("/unifiProtect/device-capability-options", RED.auth.needsPermission("unifi-protect-config.read"), async (req, res) => {
|
|
315
|
+
try {
|
|
316
|
+
const serverId = req.query.serverId;
|
|
317
|
+
const deviceType = String(req.query.deviceType || "").trim();
|
|
318
|
+
const deviceId = String(req.query.deviceId || "").trim();
|
|
319
|
+
const capabilityId = String(req.query.capability || "").trim();
|
|
320
|
+
let capabilityConfig = {};
|
|
321
|
+
|
|
322
|
+
if (!serverId) {
|
|
323
|
+
res.status(400).json({ error: "Missing serverId" });
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
if (!deviceType) {
|
|
327
|
+
res.status(400).json({ error: "Missing deviceType" });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
if (!capabilityId) {
|
|
331
|
+
res.status(400).json({ error: "Missing capability" });
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (req.query.capabilityConfig) {
|
|
336
|
+
try {
|
|
337
|
+
const parsed = JSON.parse(String(req.query.capabilityConfig));
|
|
338
|
+
capabilityConfig = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
339
|
+
} catch (error) {
|
|
340
|
+
capabilityConfig = {};
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const server = RED.nodes.getNode(serverId);
|
|
345
|
+
if (!server || typeof server.fetchCapabilityOptions !== "function") {
|
|
346
|
+
res.status(404).json({ error: "Configuration node not found" });
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const options = await server.fetchCapabilityOptions(deviceType, deviceId, capabilityId, capabilityConfig);
|
|
351
|
+
res.json(options);
|
|
352
|
+
} catch (error) {
|
|
353
|
+
res.status(500).json({ error: error.message });
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
RED.httpAdmin.get("/unifiProtect/devices", RED.auth.needsPermission("unifi-protect-config.read"), async (req, res) => {
|
|
358
|
+
try {
|
|
359
|
+
const serverId = req.query.serverId;
|
|
360
|
+
const deviceType = String(req.query.deviceType || "").trim();
|
|
361
|
+
if (!serverId) {
|
|
362
|
+
res.status(400).json({ error: "Missing serverId" });
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
if (!deviceType) {
|
|
366
|
+
res.status(400).json({ error: "Missing deviceType" });
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const server = RED.nodes.getNode(serverId);
|
|
371
|
+
if (!server || typeof server.fetchDevices !== "function") {
|
|
372
|
+
res.status(404).json({ error: "Configuration node not found" });
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
const devices = await server.fetchDevices(deviceType);
|
|
377
|
+
res.json(devices.map((device) => summarizeDevice(deviceType, device)));
|
|
378
|
+
} catch (error) {
|
|
379
|
+
res.status(500).json({ error: error.message });
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
};
|