unifi-protect 3.0.4 → 4.0.0
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.md +1 -1
- package/dist/index.d.ts +6 -6
- package/dist/index.js +6 -21
- package/dist/index.js.map +1 -1
- package/dist/protect-api-livestream.d.ts +4 -4
- package/dist/protect-api-livestream.js +21 -53
- package/dist/protect-api-livestream.js.map +1 -1
- package/dist/protect-api-updates.d.ts +11 -12
- package/dist/protect-api-updates.js +41 -48
- package/dist/protect-api-updates.js.map +1 -1
- package/dist/protect-api.d.ts +25 -40
- package/dist/protect-api.js +263 -375
- package/dist/protect-api.js.map +1 -1
- package/dist/protect-logging.js +2 -3
- package/dist/protect-logging.js.map +1 -1
- package/dist/protect-types.d.ts +41 -19
- package/dist/protect-types.js +1 -2
- package/dist/settings.d.ts +0 -2
- package/dist/settings.js +5 -13
- package/dist/settings.js.map +1 -1
- package/package.json +12 -13
package/dist/protect-api.js
CHANGED
|
@@ -1,38 +1,16 @@
|
|
|
1
|
-
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
5
|
-
}) : (function(o, m, k, k2) {
|
|
6
|
-
if (k2 === undefined) k2 = k;
|
|
7
|
-
o[k2] = m[k];
|
|
8
|
-
}));
|
|
9
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
10
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
11
|
-
}) : function(o, v) {
|
|
12
|
-
o["default"] = v;
|
|
13
|
-
});
|
|
14
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
|
15
|
-
if (mod && mod.__esModule) return mod;
|
|
16
|
-
var result = {};
|
|
17
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
18
|
-
__setModuleDefault(result, mod);
|
|
19
|
-
return result;
|
|
20
|
-
};
|
|
21
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
22
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
23
|
-
};
|
|
24
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
-
exports.ProtectApi = void 0;
|
|
26
|
-
/* Copyright(C) 2019-2022, HJD (https://github.com/hjdhjd). All rights reserved.
|
|
1
|
+
/* Copyright(C) 2019-2023, HJD (https://github.com/hjdhjd). All rights reserved.
|
|
27
2
|
*
|
|
28
3
|
* protect-api.ts: Our UniFi Protect API implementation.
|
|
29
4
|
*/
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
5
|
+
import { PROTECT_API_ERROR_LIMIT, PROTECT_API_RETRY_INTERVAL, PROTECT_API_TIMEOUT } from "./settings.js";
|
|
6
|
+
import fetch, { AbortError, FetchError, Headers } from "node-fetch";
|
|
7
|
+
import https from "node:https";
|
|
8
|
+
import { AbortController } from "abort-controller";
|
|
9
|
+
import { EventEmitter } from "node:events";
|
|
10
|
+
import { ProtectApiEvents } from "./protect-api-updates.js";
|
|
11
|
+
import { ProtectLivestream } from "./protect-api-livestream.js";
|
|
12
|
+
import WebSocket from "ws";
|
|
13
|
+
import util from "node:util";
|
|
36
14
|
/*
|
|
37
15
|
* The UniFi Protect API is largely undocumented and has been reverse engineered mostly through
|
|
38
16
|
* the web interface, and trial and error.
|
|
@@ -42,58 +20,67 @@ const util_1 = __importDefault(require("util"));
|
|
|
42
20
|
* 1. Login to the UniFi Protect NVR device and acquire security credentials for further calls to the API.
|
|
43
21
|
*
|
|
44
22
|
* 2. Enumerate the list of UniFi Protect devices by calling the bootstrap URL. This
|
|
45
|
-
* contains almost everything you would want to know about this particular UniFi Protect
|
|
46
|
-
*
|
|
23
|
+
* contains almost everything you would want to know about this particular UniFi Protect controller.
|
|
24
|
+
*
|
|
25
|
+
* 3. Use the events API to track updates to the devices detected by the Protect controller.
|
|
47
26
|
*
|
|
48
27
|
* Those are the basics that gets us up and running.
|
|
49
28
|
*/
|
|
50
|
-
class ProtectApi {
|
|
29
|
+
export class ProtectApi extends EventEmitter {
|
|
51
30
|
// Initialize this instance with our login information.
|
|
52
|
-
constructor(
|
|
31
|
+
constructor(log) {
|
|
32
|
+
// Initialize our parent.
|
|
33
|
+
super();
|
|
53
34
|
// If we didn't get passed a logging parameter, by default we log to the console.
|
|
54
35
|
if (!log) {
|
|
55
36
|
log = {
|
|
56
37
|
/* eslint-disable no-console */
|
|
57
38
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
58
39
|
debug: (message, ...parameters) => { },
|
|
59
|
-
error: (message, ...parameters) => console.error(
|
|
60
|
-
info: (message, ...parameters) => console.log(
|
|
61
|
-
warn: (message, ...parameters) => console.log(
|
|
40
|
+
error: (message, ...parameters) => console.error(message, ...parameters),
|
|
41
|
+
info: (message, ...parameters) => console.log(message, ...parameters),
|
|
42
|
+
warn: (message, ...parameters) => console.log(message, ...parameters)
|
|
62
43
|
/* eslint-enable no-console */
|
|
63
44
|
};
|
|
64
45
|
}
|
|
65
46
|
this._bootstrap = null;
|
|
66
|
-
this.
|
|
67
|
-
this.
|
|
68
|
-
|
|
69
|
-
|
|
47
|
+
this._eventsWs = null;
|
|
48
|
+
this._log = {
|
|
49
|
+
debug: (message, ...parameters) => log?.debug(this.name + ": " + message, ...parameters),
|
|
50
|
+
error: (message, ...parameters) => log?.error(this.name + ": API error: " + message, ...parameters),
|
|
51
|
+
info: (message, ...parameters) => log?.info(this.name + ": " + message, ...parameters),
|
|
52
|
+
warn: (message, ...parameters) => log?.warn(this.name + ": " + message, ...parameters)
|
|
53
|
+
};
|
|
70
54
|
this.apiErrorCount = 0;
|
|
71
55
|
this.apiLastSuccess = 0;
|
|
72
|
-
this.
|
|
73
|
-
this.httpsAgent = new https_1.default.Agent({ rejectUnauthorized: false });
|
|
56
|
+
this.httpsAgent = new https.Agent({ rejectUnauthorized: false });
|
|
74
57
|
this.isAdminUser = false;
|
|
75
|
-
this.isLoggedIn = false;
|
|
76
|
-
this.isLoginRefresh = false;
|
|
77
|
-
this._log = log;
|
|
78
58
|
this.loginAge = 0;
|
|
79
59
|
this.loginAttempt = null;
|
|
60
|
+
this.loginRefreshTimer = null;
|
|
61
|
+
this.nvrAddress = "";
|
|
62
|
+
this.username = "";
|
|
63
|
+
this.password = "";
|
|
64
|
+
this.clearLoginCredentials();
|
|
65
|
+
}
|
|
66
|
+
// Login to the Protect controller and terminate any existing login we might have.
|
|
67
|
+
async login(nvrAddress, username, password) {
|
|
68
|
+
this.clearLoginCredentials();
|
|
80
69
|
this.nvrAddress = nvrAddress;
|
|
81
70
|
this.username = username;
|
|
82
71
|
this.password = password;
|
|
83
|
-
this.
|
|
72
|
+
return this.loginController();
|
|
84
73
|
}
|
|
85
|
-
//
|
|
86
|
-
async
|
|
87
|
-
// We only need to acquire a token if we aren't already logged in, or we don't already have a token
|
|
88
|
-
|
|
89
|
-
if (this.isLoggedIn || this.headers.has("X-CSRF-Token") || this.headers.has("Authorization")) {
|
|
74
|
+
// Acquire a CSRF token for our API session if needed.
|
|
75
|
+
async acquireCsrfToken() {
|
|
76
|
+
// We only need to acquire a token if we aren't already logged in, or we don't already have a token.
|
|
77
|
+
if (this.headers.has("X-CSRF-Token")) {
|
|
90
78
|
return true;
|
|
91
79
|
}
|
|
92
|
-
// UniFi OS has cross-site request forgery protection built into it's web management UI.
|
|
93
|
-
//
|
|
94
|
-
// and see ifing there's a CSRF token waiting for us.
|
|
80
|
+
// UniFi OS has cross-site request forgery protection built into it's web management UI. We use this fact to fingerprint it
|
|
81
|
+
// by connecting directly to the supplied Protect controller address and see if there's a CSRF token waiting for us.
|
|
95
82
|
const response = await this.fetch("https://" + this.nvrAddress, { method: "GET" }, false);
|
|
96
|
-
if (response
|
|
83
|
+
if (response?.ok) {
|
|
97
84
|
const csrfToken = response.headers.get("X-CSRF-Token");
|
|
98
85
|
// We found a token.
|
|
99
86
|
if (csrfToken) {
|
|
@@ -101,75 +88,57 @@ class ProtectApi {
|
|
|
101
88
|
return true;
|
|
102
89
|
}
|
|
103
90
|
}
|
|
104
|
-
//
|
|
91
|
+
// Something went wrong.
|
|
105
92
|
return false;
|
|
106
93
|
}
|
|
107
94
|
// Login to the UniFi Protect API.
|
|
108
|
-
async
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
if (now > (this.loginAge + (settings_1.PROTECT_LOGIN_REFRESH_INTERVAL * 1000))) {
|
|
112
|
-
if (this.loginAge) {
|
|
113
|
-
this.isLoginRefresh = true;
|
|
114
|
-
}
|
|
115
|
-
this.clearLoginCredentials();
|
|
116
|
-
}
|
|
117
|
-
// If we're already logged in, and it's not time to renew our credentials, we're done.
|
|
118
|
-
if (this.isLoggedIn) {
|
|
119
|
-
this.isLoginRefresh = false;
|
|
95
|
+
async loginController() {
|
|
96
|
+
// If we're already logged in, we're done.
|
|
97
|
+
if (this.headers.has("Cookie") && this.headers.has("X-CSRF-Token")) {
|
|
120
98
|
return true;
|
|
121
99
|
}
|
|
122
|
-
// Make sure we have a token, or get one if needed.
|
|
123
|
-
if (!(await this.
|
|
100
|
+
// Make sure we have a CSRF token, or get one if needed.
|
|
101
|
+
if (!(await this.acquireCsrfToken())) {
|
|
124
102
|
this.clearLoginCredentials();
|
|
125
103
|
return false;
|
|
126
104
|
}
|
|
127
105
|
// Log us in.
|
|
128
|
-
const response = await this.fetch(this.
|
|
129
|
-
body: JSON.stringify({ password: this.password, username: this.username }),
|
|
106
|
+
const response = await this.fetch(this.getApiEndpoint("login"), {
|
|
107
|
+
body: JSON.stringify({ password: this.password, rememberMe: "true", username: this.username }),
|
|
130
108
|
method: "POST"
|
|
131
109
|
});
|
|
132
|
-
|
|
110
|
+
// Something went wrong with the login call, possibly a controller reboot or failure.
|
|
111
|
+
if (!response?.ok) {
|
|
133
112
|
this.clearLoginCredentials();
|
|
134
113
|
return false;
|
|
135
114
|
}
|
|
136
|
-
// We're logged in.
|
|
137
|
-
this.loginAge = now;
|
|
138
|
-
this.isLoggedIn = true;
|
|
139
|
-
// Configure headers.
|
|
115
|
+
// We're logged in. Let's configure our headers.
|
|
140
116
|
const csrfToken = response.headers.get("X-CSRF-Token");
|
|
141
117
|
const cookie = response.headers.get("Set-Cookie");
|
|
118
|
+
// Save the refreshed cookie and CSRF token for future API calls and we're done.
|
|
142
119
|
if (csrfToken && cookie && this.headers.has("X-CSRF-Token")) {
|
|
143
120
|
this.headers.set("Cookie", cookie);
|
|
144
121
|
this.headers.set("X-CSRF-Token", csrfToken);
|
|
122
|
+
this.emit("login", true);
|
|
145
123
|
return true;
|
|
146
124
|
}
|
|
147
125
|
// Clear out our login credentials and reset for another try.
|
|
148
126
|
this.clearLoginCredentials();
|
|
127
|
+
this.emit("login", false);
|
|
149
128
|
return false;
|
|
150
129
|
}
|
|
151
|
-
//
|
|
152
|
-
|
|
153
|
-
// We want to ensure we aren't trying simultaneous login attempts and creating a potential DoS, so we wait
|
|
154
|
-
// for one attempt to complete before beginning another.
|
|
155
|
-
if (!this.loginAttempt) {
|
|
156
|
-
this.loginAttempt = this.loginNvr();
|
|
157
|
-
this.loginAttempt.finally(() => this.loginAttempt = null);
|
|
158
|
-
}
|
|
159
|
-
return this.loginAttempt;
|
|
160
|
-
}
|
|
161
|
-
// Get our UniFi Protect NVR configuration.
|
|
162
|
-
async bootstrapProtect() {
|
|
130
|
+
// Attempt to retrieve the bootstrap configuration from the Protect NVR.
|
|
131
|
+
async bootstrapController(retry) {
|
|
163
132
|
// Log us in if needed.
|
|
164
|
-
if (!(await this.
|
|
165
|
-
return false;
|
|
133
|
+
if (!(await this.loginController())) {
|
|
134
|
+
return retry ? this.bootstrapController(false) : false;
|
|
166
135
|
}
|
|
167
|
-
const response = await this.fetch(this.
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
// Clear out our login credentials and reset for another try.
|
|
136
|
+
const response = await this.fetch(this.getApiEndpoint("bootstrap"));
|
|
137
|
+
// Something went wrong. Preemptively clear our login credentials and inform the user.
|
|
138
|
+
if (!response?.ok) {
|
|
171
139
|
this.clearLoginCredentials();
|
|
172
|
-
|
|
140
|
+
this.log.error("Unable to retrieve the UniFi Protect controller configuration.%s", retry ? " Retrying." : "");
|
|
141
|
+
return retry ? this.bootstrapController(false) : false;
|
|
173
142
|
}
|
|
174
143
|
// Now let's get our NVR configuration information.
|
|
175
144
|
let data = null;
|
|
@@ -178,45 +147,36 @@ class ProtectApi {
|
|
|
178
147
|
}
|
|
179
148
|
catch (error) {
|
|
180
149
|
data = null;
|
|
181
|
-
this.log.error("
|
|
150
|
+
this.log.error("Unable to parse response from UniFi Protect. Will retry again later.");
|
|
182
151
|
}
|
|
183
|
-
//
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
// Clear out our login credentials and reset for another try.
|
|
187
|
-
this.clearLoginCredentials();
|
|
188
|
-
return false;
|
|
189
|
-
}
|
|
190
|
-
// On launch, let the user know we made it.
|
|
191
|
-
const firstRun = this.bootstrap ? false : true;
|
|
152
|
+
// Is this the first time we're bootstrapping?
|
|
153
|
+
const isFirstRun = this.bootstrap ? false : true;
|
|
154
|
+
// Set the new bootstrap.
|
|
192
155
|
this._bootstrap = data;
|
|
193
|
-
if (firstRun && !this.isLoginRefresh) {
|
|
194
|
-
this.log.info("%s: Connected to the UniFi Protect controller API (address: %s mac: %s).", this.getNvrName(), data.nvr.host, data.nvr.mac);
|
|
195
|
-
}
|
|
196
|
-
// Capture the bootstrap if we're debugging.
|
|
197
|
-
this.log.debug(util_1.default.inspect(this.bootstrap, { colors: true, depth: null, sorted: true }));
|
|
198
156
|
// Check for admin user privileges or role changes.
|
|
199
|
-
this.checkAdminUserStatus(
|
|
157
|
+
this.checkAdminUserStatus(isFirstRun);
|
|
158
|
+
// Notify our users.
|
|
159
|
+
this.emit("bootstrap", this.bootstrap);
|
|
200
160
|
// We're good. Now connect to the event listener API.
|
|
201
|
-
return this.
|
|
161
|
+
return this.launchEventsWs();
|
|
202
162
|
}
|
|
203
163
|
// Connect to the realtime update events API.
|
|
204
|
-
async
|
|
205
|
-
var _a, _b, _c;
|
|
164
|
+
async launchEventsWs() {
|
|
206
165
|
// Log us in if needed.
|
|
207
|
-
if (!(await this.
|
|
166
|
+
if (!(await this.loginController())) {
|
|
208
167
|
return false;
|
|
209
168
|
}
|
|
210
169
|
// If we already have a listener, we're already all set.
|
|
211
|
-
if (this.
|
|
170
|
+
if (this._eventsWs) {
|
|
212
171
|
return true;
|
|
213
172
|
}
|
|
214
|
-
|
|
215
|
-
|
|
173
|
+
// Launch the realtime events WebSocket. We need to hand it the last update ID we know about in order
|
|
174
|
+
// to ensure we don't miss any actual updates since we last pulled the bootstrap configuration.
|
|
175
|
+
const params = new URLSearchParams({ lastUpdateId: this.bootstrap?.lastUpdateId ?? "" });
|
|
216
176
|
try {
|
|
217
|
-
const ws = new
|
|
177
|
+
const ws = new WebSocket("wss://" + this.nvrAddress + "/proxy/protect/ws/updates?" + params.toString(), {
|
|
218
178
|
headers: {
|
|
219
|
-
Cookie:
|
|
179
|
+
Cookie: this.headers.get("Cookie") ?? ""
|
|
220
180
|
},
|
|
221
181
|
rejectUnauthorized: false
|
|
222
182
|
});
|
|
@@ -225,97 +185,62 @@ class ProtectApi {
|
|
|
225
185
|
this._eventsWs = null;
|
|
226
186
|
return false;
|
|
227
187
|
}
|
|
188
|
+
let messageHandler;
|
|
189
|
+
// Cleanup after ourselves if our websocket closes for some resaon.
|
|
190
|
+
ws.once("close", () => {
|
|
191
|
+
this._eventsWs = null;
|
|
192
|
+
if (messageHandler) {
|
|
193
|
+
ws.removeListener("message", messageHandler);
|
|
194
|
+
messageHandler = null;
|
|
195
|
+
}
|
|
196
|
+
});
|
|
228
197
|
// Handle any websocket errors.
|
|
229
198
|
ws.once("error", (error) => {
|
|
230
199
|
// If we're closing before fully established it's because we're shutting down the API - ignore it.
|
|
231
200
|
if (error.message !== "WebSocket was closed before the connection was established") {
|
|
232
|
-
this.log.error(
|
|
201
|
+
this.log.error(error.toString());
|
|
233
202
|
}
|
|
234
203
|
ws.terminate();
|
|
235
|
-
this._eventsWs = null;
|
|
236
204
|
});
|
|
237
|
-
//
|
|
238
|
-
ws.
|
|
239
|
-
this.
|
|
205
|
+
// Process messages as they come in.
|
|
206
|
+
ws.on("message", messageHandler = (event) => {
|
|
207
|
+
const packet = ProtectApiEvents.decodePacket(this.log, event);
|
|
208
|
+
if (!packet) {
|
|
209
|
+
this.log.error("Unable to process message from the realtime update events API.");
|
|
210
|
+
ws.terminate();
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
// Emit the decoded packet for users.
|
|
214
|
+
this.emit("message", packet);
|
|
240
215
|
});
|
|
241
216
|
// Make the websocket available, and then we're done.
|
|
242
217
|
this._eventsWs = ws;
|
|
243
|
-
if (!this.isLoginRefresh) {
|
|
244
|
-
this.log.info("%s: Connected to the UniFi Protect realtime update events API.", this.getNvrName());
|
|
245
|
-
}
|
|
246
218
|
}
|
|
247
219
|
catch (error) {
|
|
248
|
-
this.log.error("
|
|
220
|
+
this.log.error("Error connecting to the realtime update events API: %s", error);
|
|
249
221
|
}
|
|
250
222
|
return true;
|
|
251
223
|
}
|
|
252
|
-
//
|
|
253
|
-
|
|
254
|
-
//
|
|
255
|
-
|
|
256
|
-
for (const newDevice of newDeviceList) {
|
|
257
|
-
// We already know about this device.
|
|
258
|
-
if (currentDeviceList === null || currentDeviceList === void 0 ? void 0 : currentDeviceList.some((x) => x.mac === newDevice.mac)) {
|
|
259
|
-
continue;
|
|
260
|
-
}
|
|
261
|
-
// We only want to discover adopted devices.
|
|
262
|
-
if (!newDevice.isAdopted) {
|
|
263
|
-
continue;
|
|
264
|
-
}
|
|
265
|
-
// We've discovered a new device.
|
|
266
|
-
this.log.info("%s: Discovered %s: %s.", this.getNvrName(), newDevice.modelKey, this.getDeviceName(newDevice, newDevice.name, true));
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
// Notify the user about any devices that have disappeared.
|
|
270
|
-
if (currentDeviceList) {
|
|
271
|
-
for (const existingDevice of currentDeviceList) {
|
|
272
|
-
// This device still is visible.
|
|
273
|
-
if (newDeviceList === null || newDeviceList === void 0 ? void 0 : newDeviceList.some((x) => x.mac === existingDevice.mac)) {
|
|
274
|
-
continue;
|
|
275
|
-
}
|
|
276
|
-
// We've had a device disappear.
|
|
277
|
-
this.log.debug("%s: Detected %s removal.", this.getFullName(existingDevice), existingDevice.modelKey);
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
// Return the updated list of devices.
|
|
281
|
-
return newDeviceList !== null && newDeviceList !== void 0 ? newDeviceList : null;
|
|
282
|
-
}
|
|
283
|
-
// Get the list of UniFi Protect devices associated with a NVR.
|
|
284
|
-
async refreshDevices() {
|
|
285
|
-
var _a, _b, _c, _d;
|
|
286
|
-
// Refresh the configuration from the NVR.
|
|
287
|
-
if (!(await this.bootstrapProtect())) {
|
|
288
|
-
return false;
|
|
289
|
-
}
|
|
290
|
-
this.log.debug(util_1.default.inspect(this.bootstrap, { colors: true, depth: null, sorted: true }));
|
|
291
|
-
// We currently know about the following device classes:
|
|
292
|
-
// - cameras (including doorbells)
|
|
293
|
-
// - lights
|
|
294
|
-
// - sensors
|
|
295
|
-
// - viewers
|
|
296
|
-
this._cameras = this.refreshDeviceClass(this.cameras, (_a = this.bootstrap) === null || _a === void 0 ? void 0 : _a.cameras);
|
|
297
|
-
this._lights = this.refreshDeviceClass(this.lights, (_b = this.bootstrap) === null || _b === void 0 ? void 0 : _b.lights);
|
|
298
|
-
this._sensors = this.refreshDeviceClass(this.sensors, (_c = this.bootstrap) === null || _c === void 0 ? void 0 : _c.sensors);
|
|
299
|
-
this._viewers = this.refreshDeviceClass(this.viewers, (_d = this.bootstrap) === null || _d === void 0 ? void 0 : _d.viewers);
|
|
300
|
-
return true;
|
|
224
|
+
// Get our UniFi Protect NVR configuration.
|
|
225
|
+
async getBootstrap() {
|
|
226
|
+
// Bootstrap the controller, and attempt to retry the bootstrap if it fails.
|
|
227
|
+
return this.bootstrapController(true);
|
|
301
228
|
}
|
|
302
229
|
// Validate if all RTSP channels enabled on all cameras.
|
|
303
230
|
isAllRtspConfigured() {
|
|
304
|
-
var _a, _b;
|
|
305
231
|
// Look for any cameras with any non-RTSP enabled channels.
|
|
306
|
-
return
|
|
232
|
+
return this.bootstrap?.cameras?.some(camera => camera.channels?.some(channel => !channel.isRtspEnabled)) ? true : false;
|
|
307
233
|
}
|
|
308
234
|
// Check admin privileges.
|
|
309
|
-
checkAdminUserStatus(
|
|
310
|
-
|
|
311
|
-
if (!((_a = this.bootstrap) === null || _a === void 0 ? void 0 : _a.users)) {
|
|
235
|
+
checkAdminUserStatus(isFirstRun = false) {
|
|
236
|
+
if (!this.bootstrap?.users) {
|
|
312
237
|
return false;
|
|
313
238
|
}
|
|
314
239
|
// Save our prior state so we can detect role changes without having to restart.
|
|
315
240
|
const oldAdminStatus = this.isAdminUser;
|
|
316
241
|
// Find this user.
|
|
317
|
-
const user =
|
|
318
|
-
if (!
|
|
242
|
+
const user = this.bootstrap?.users.find((x) => x.id === this.bootstrap?.authUserId);
|
|
243
|
+
if (!user?.allPermissions) {
|
|
319
244
|
return false;
|
|
320
245
|
}
|
|
321
246
|
// Let's figure out this user's permissions.
|
|
@@ -337,36 +262,36 @@ class ProtectApi {
|
|
|
337
262
|
}
|
|
338
263
|
this.isAdminUser = newAdminStatus;
|
|
339
264
|
// Only admin users can activate RTSP streams. Inform the user on startup, or if we detect a role change.
|
|
340
|
-
if (
|
|
341
|
-
this.log.info("
|
|
265
|
+
if (isFirstRun && !this.isAdminUser) {
|
|
266
|
+
this.log.info("The user '%s' requires the Administrator role in order to automatically configure camera RTSP streams.", this.username);
|
|
342
267
|
}
|
|
343
|
-
else if (!
|
|
344
|
-
this.log.info("
|
|
268
|
+
else if (!isFirstRun && (oldAdminStatus !== this.isAdminUser)) {
|
|
269
|
+
this.log.info("Detected a role change for user '%s': the Administrator role has been %s.", this.username, this.isAdminUser ? "enabled" : "disabled");
|
|
345
270
|
}
|
|
346
271
|
return true;
|
|
347
272
|
}
|
|
348
|
-
// Update a
|
|
349
|
-
async
|
|
273
|
+
// Update a Protect device object.
|
|
274
|
+
async updateDevice(device, payload) {
|
|
350
275
|
// No device object, we're done.
|
|
351
276
|
if (!device) {
|
|
352
277
|
return null;
|
|
353
278
|
}
|
|
354
279
|
// Log us in if needed.
|
|
355
|
-
if (!(await this.
|
|
280
|
+
if (!(await this.loginController())) {
|
|
356
281
|
return null;
|
|
357
282
|
}
|
|
358
283
|
// Only admin users can update JSON objects.
|
|
359
284
|
if (!this.isAdminUser) {
|
|
360
285
|
return null;
|
|
361
286
|
}
|
|
362
|
-
this.log.debug("%s: %s", this.getFullName(device),
|
|
287
|
+
this.log.debug("%s: %s", this.getFullName(device), util.inspect(payload, { colors: true, depth: null, sorted: true }));
|
|
363
288
|
// Update Protect with the new configuration.
|
|
364
|
-
const response = await this.fetch(this.
|
|
289
|
+
const response = await this.fetch(this.getApiEndpoint(device.modelKey) + (device.modelKey === "nvr" ? "" : "/" + device.id), {
|
|
365
290
|
body: JSON.stringify(payload),
|
|
366
291
|
method: "PATCH"
|
|
367
292
|
});
|
|
368
|
-
if (!
|
|
369
|
-
this.log.error("%s: Unable to configure the
|
|
293
|
+
if (!response?.ok) {
|
|
294
|
+
this.log.error("%s: Unable to configure the %s: %s.", this.getFullName(device), device.modelKey, response?.status);
|
|
370
295
|
return null;
|
|
371
296
|
}
|
|
372
297
|
// We successfully set the message, return the updated device object.
|
|
@@ -379,18 +304,18 @@ class ProtectApi {
|
|
|
379
304
|
return null;
|
|
380
305
|
}
|
|
381
306
|
// Update Protect with the new configuration.
|
|
382
|
-
const response = await this.fetch(this.
|
|
307
|
+
const response = await this.fetch(this.getApiEndpoint(device.modelKey) + "/" + device.id, {
|
|
383
308
|
body: JSON.stringify({ channels: device.channels }),
|
|
384
309
|
method: "PATCH"
|
|
385
310
|
}, true, false);
|
|
386
311
|
// Since we took responsibility for interpreting the outcome of the fetch, we need to check for any errors.
|
|
387
|
-
if (!response || !
|
|
312
|
+
if (!response || !response?.ok) {
|
|
388
313
|
this.apiErrorCount++;
|
|
389
|
-
if (
|
|
314
|
+
if (response?.status === 403) {
|
|
390
315
|
this.log.error("%s: Insufficient privileges to enable RTSP on all channels. Please ensure this username has the Administrator role assigned in UniFi Protect.", this.getFullName(device));
|
|
391
316
|
}
|
|
392
317
|
else {
|
|
393
|
-
this.log.error("%s: Unable to enable RTSP on all channels: %s.", this.getFullName(device), response
|
|
318
|
+
this.log.error("%s: Unable to enable RTSP on all channels: %s.", this.getFullName(device), response?.status);
|
|
394
319
|
}
|
|
395
320
|
// We still return our camera object if there is at least one RTSP channel enabled.
|
|
396
321
|
return device;
|
|
@@ -401,69 +326,14 @@ class ProtectApi {
|
|
|
401
326
|
// Everything worked, save the new channel array.
|
|
402
327
|
return await response.json();
|
|
403
328
|
}
|
|
404
|
-
// Update a light object.
|
|
405
|
-
async updateLight(device, payload) {
|
|
406
|
-
// No device object, we're done.
|
|
407
|
-
if (!device) {
|
|
408
|
-
return null;
|
|
409
|
-
}
|
|
410
|
-
// Log us in if needed.
|
|
411
|
-
if (!(await this.login())) {
|
|
412
|
-
return null;
|
|
413
|
-
}
|
|
414
|
-
// Only admin users can update JSON objects.
|
|
415
|
-
if (!this.isAdminUser) {
|
|
416
|
-
return null;
|
|
417
|
-
}
|
|
418
|
-
this.log.error("%s: %s", this.getFullName(device), util_1.default.inspect(payload, { colors: true, depth: null, sorted: true }));
|
|
419
|
-
// Update Protect with the new configuration.
|
|
420
|
-
const response = await this.fetch(this.lightsUrl() + "/" + device.id, {
|
|
421
|
-
body: JSON.stringify(payload),
|
|
422
|
-
method: "PATCH"
|
|
423
|
-
});
|
|
424
|
-
if (!(response === null || response === void 0 ? void 0 : response.ok)) {
|
|
425
|
-
this.log.debug("%s: Unable to configure the light: %s.", this.getFullName(device), response === null || response === void 0 ? void 0 : response.status);
|
|
426
|
-
return null;
|
|
427
|
-
}
|
|
428
|
-
// We successfully set the message, return the updated device object.
|
|
429
|
-
return await response.json();
|
|
430
|
-
}
|
|
431
|
-
// Update a viewer object.
|
|
432
|
-
async updateViewer(device, payload) {
|
|
433
|
-
// No device object, we're done.
|
|
434
|
-
if (!device) {
|
|
435
|
-
return null;
|
|
436
|
-
}
|
|
437
|
-
// Log us in if needed.
|
|
438
|
-
if (!(await this.login())) {
|
|
439
|
-
return null;
|
|
440
|
-
}
|
|
441
|
-
// Only admin users can update JSON objects.
|
|
442
|
-
if (!this.isAdminUser) {
|
|
443
|
-
return null;
|
|
444
|
-
}
|
|
445
|
-
this.log.debug("%s: %s", this.getFullName(device), util_1.default.inspect(payload, { colors: true, depth: null, sorted: true }));
|
|
446
|
-
// Update Protect with the new configuration.
|
|
447
|
-
const response = await this.fetch(this.viewersUrl() + "/" + device.id, {
|
|
448
|
-
body: JSON.stringify(payload),
|
|
449
|
-
method: "PATCH"
|
|
450
|
-
});
|
|
451
|
-
if (!(response === null || response === void 0 ? void 0 : response.ok)) {
|
|
452
|
-
this.log.error("%s: Unable to configure the viewer: %s.", this.getFullName(device), response === null || response === void 0 ? void 0 : response.status);
|
|
453
|
-
return null;
|
|
454
|
-
}
|
|
455
|
-
// We successfully set the message, return the updated device object.
|
|
456
|
-
return await response.json();
|
|
457
|
-
}
|
|
458
329
|
// Enable RTSP stream support on an attached Protect device.
|
|
459
330
|
async enableRtsp(device) {
|
|
460
|
-
var _a;
|
|
461
331
|
// Make sure we have the permissions to modify the camera JSON.
|
|
462
332
|
if (!(await this.canModifyCamera(device))) {
|
|
463
333
|
return null;
|
|
464
334
|
}
|
|
465
335
|
// Do we have any non-RTSP enabled channels? If not, we're done.
|
|
466
|
-
if (!
|
|
336
|
+
if (!device.channels?.some(channel => !channel.isRtspEnabled)) {
|
|
467
337
|
return device;
|
|
468
338
|
}
|
|
469
339
|
// Enable RTSP on all available channels.
|
|
@@ -474,119 +344,49 @@ class ProtectApi {
|
|
|
474
344
|
// Update the camera channel JSON with our edits.
|
|
475
345
|
return this.updateCameraChannels(device);
|
|
476
346
|
}
|
|
477
|
-
// Get the bootstrap JSON.
|
|
478
|
-
get bootstrap() {
|
|
479
|
-
return this._bootstrap;
|
|
480
|
-
}
|
|
481
|
-
// Return all the cameras on this controller.
|
|
482
|
-
get cameras() {
|
|
483
|
-
return this._cameras;
|
|
484
|
-
}
|
|
485
|
-
// Get the events websocket.
|
|
486
|
-
get eventsWs() {
|
|
487
|
-
return this._eventsWs;
|
|
488
|
-
}
|
|
489
|
-
// Return all the lights on this controller.
|
|
490
|
-
get lights() {
|
|
491
|
-
return this._lights;
|
|
492
|
-
}
|
|
493
|
-
// Utility to access the logging functions, used by other classes in this library.
|
|
494
|
-
get log() {
|
|
495
|
-
return this._log;
|
|
496
|
-
}
|
|
497
|
-
// Return all the sensors on this controller.
|
|
498
|
-
get sensors() {
|
|
499
|
-
return this._sensors;
|
|
500
|
-
}
|
|
501
|
-
// Return all the viewers on this controller.
|
|
502
|
-
get viewers() {
|
|
503
|
-
return this._viewers;
|
|
504
|
-
}
|
|
505
|
-
// Utility to generate a nicely formatted NVR string.
|
|
506
|
-
getNvrName() {
|
|
507
|
-
var _a;
|
|
508
|
-
// Our NVR string, if it exists, appears as:
|
|
509
|
-
// NVR [NVR Type].
|
|
510
|
-
// Otherwise, we appear as NVRaddress.
|
|
511
|
-
if ((_a = this.bootstrap) === null || _a === void 0 ? void 0 : _a.nvr) {
|
|
512
|
-
return this.bootstrap.nvr.name + " [" + this.bootstrap.nvr.type + "]";
|
|
513
|
-
}
|
|
514
|
-
else {
|
|
515
|
-
return this.nvrAddress;
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
347
|
// Utility to generate a nicely formatted device string.
|
|
519
|
-
getDeviceName(device, name = device
|
|
348
|
+
getDeviceName(device, name = device?.name, deviceInfo = false) {
|
|
520
349
|
// Validate our inputs.
|
|
521
350
|
if (!device) {
|
|
522
351
|
return "";
|
|
523
352
|
}
|
|
524
353
|
// Include the host address information, if we have it.
|
|
525
354
|
const host = (("host" in device) && device.host) ? "address: " + device.host + " " : "";
|
|
355
|
+
const type = (("marketName" in device) && device.marketName) ? device.marketName : device.type;
|
|
526
356
|
// A completely enumerated device will appear as:
|
|
527
357
|
// Device Name [Device Type] (address: IP address, mac: MAC address).
|
|
528
|
-
return name + " [" +
|
|
529
|
-
(deviceInfo ? " (" + host + "mac: " + device.mac + ")" : "");
|
|
358
|
+
return name + " [" + type + "]" + (deviceInfo ? " (" + host + "mac: " + device.mac + ")" : "");
|
|
530
359
|
}
|
|
531
360
|
// Utility to generate a nicely formatted NVR and device string.
|
|
532
361
|
getFullName(device) {
|
|
533
362
|
const deviceName = this.getDeviceName(device);
|
|
534
363
|
// Returns: NVR [NVR Type] Device Name [Device Type]
|
|
535
|
-
return this.
|
|
536
|
-
}
|
|
537
|
-
// Return the URL to directly access cameras.
|
|
538
|
-
camerasUrl() {
|
|
539
|
-
// Boostrapping a UniFi OS device is done through: https://protect-nvr-ip/proxy/protect/api/cameras/CAMERAID.
|
|
540
|
-
return "https://" + this.nvrAddress + "/proxy/protect/api/cameras";
|
|
541
|
-
}
|
|
542
|
-
// Return the URL to directly access lights.
|
|
543
|
-
lightsUrl() {
|
|
544
|
-
// Boostrapping a UniFi OS device is done through: https://protect-nvr-ip/proxy/protect/api/lights/LIGHTID.
|
|
545
|
-
return "https://" + this.nvrAddress + "/proxy/protect/api/lights";
|
|
546
|
-
}
|
|
547
|
-
// Return the URL to directly access viewers.
|
|
548
|
-
viewersUrl() {
|
|
549
|
-
// Boostrapping a UniFi OS device is done through: https://protect-nvr-ip/proxy/protect/api/viewers/VIEWERID.
|
|
550
|
-
return "https://" + this.nvrAddress + "/proxy/protect/api/viewers";
|
|
551
|
-
}
|
|
552
|
-
// Return the URL to the websocket API endpoint.
|
|
553
|
-
wsUrl() {
|
|
554
|
-
// Boostrapping a UniFi OS device is done through: https://protect-nvr-ip/proxy/protect/api/ws/WEBSOCKET.
|
|
555
|
-
return "https://" + this.nvrAddress + "/proxy/protect/api/ws";
|
|
556
|
-
}
|
|
557
|
-
// Return the right Protect NVR authentication URL.
|
|
558
|
-
authUrl() {
|
|
559
|
-
// Authenticating a UniFi OS device is done through: https://protect-nvr-ip/api/auth/login.
|
|
560
|
-
return "https://" + this.nvrAddress + "/api/auth/login";
|
|
561
|
-
}
|
|
562
|
-
// Return the right Protect NVR bootstrap URL.
|
|
563
|
-
bootstrapUrl() {
|
|
564
|
-
// Boostrapping a UniFi OS device is done through: https://protect-nvr-ip/proxy/protect/api/bootstrap.
|
|
565
|
-
return "https://" + this.nvrAddress + "/proxy/protect/api/bootstrap";
|
|
566
|
-
}
|
|
567
|
-
// Return the realtime system events API URL.
|
|
568
|
-
systemUrl() {
|
|
569
|
-
return "wss://" + this.nvrAddress + "/api/ws/system";
|
|
570
|
-
}
|
|
571
|
-
// Return the realtime update events API URL.
|
|
572
|
-
updatesUrl() {
|
|
573
|
-
return "wss://" + this.nvrAddress + "/proxy/protect/ws/updates";
|
|
364
|
+
return this.name + (deviceName.length ? " " + deviceName : "");
|
|
574
365
|
}
|
|
575
366
|
// Utility to clear out old login credentials or attempts.
|
|
576
367
|
clearLoginCredentials() {
|
|
577
368
|
this.isAdminUser = false;
|
|
578
|
-
this.isLoggedIn = false;
|
|
579
369
|
this.loginAge = 0;
|
|
580
370
|
this.loginAttempt = null;
|
|
581
371
|
this._bootstrap = null;
|
|
372
|
+
if (this.loginRefreshTimer) {
|
|
373
|
+
clearTimeout(this.loginRefreshTimer);
|
|
374
|
+
}
|
|
375
|
+
this.loginRefreshTimer = null;
|
|
376
|
+
// Save our CSRF token, if we have one.
|
|
377
|
+
const csrfToken = this.headers?.get("X-CSRF-Token");
|
|
582
378
|
// Initialize the headers we need.
|
|
583
|
-
this.headers = new
|
|
379
|
+
this.headers = new Headers();
|
|
584
380
|
this.headers.set("Content-Type", "application/json");
|
|
381
|
+
// Restore the CSRF token if we have one.
|
|
382
|
+
if (csrfToken) {
|
|
383
|
+
this.headers.set("X-CSRF-Token", csrfToken);
|
|
384
|
+
}
|
|
585
385
|
}
|
|
586
386
|
// Utility to validate that we have the privileges we need to modify the camera JSON.
|
|
587
387
|
async canModifyCamera(device) {
|
|
588
388
|
// Log us in if needed.
|
|
589
|
-
if (!(await this.
|
|
389
|
+
if (!(await this.loginController())) {
|
|
590
390
|
return false;
|
|
591
391
|
}
|
|
592
392
|
// Only admin users can activate RTSP streams.
|
|
@@ -600,15 +400,32 @@ class ProtectApi {
|
|
|
600
400
|
return true;
|
|
601
401
|
}
|
|
602
402
|
// Return a WebSocket URL endpoint from the Protect controller for Protect API services (e.g. livestream, talkback).
|
|
603
|
-
async getWsEndpoint(
|
|
604
|
-
|
|
403
|
+
async getWsEndpoint(endpoint, params) {
|
|
404
|
+
return this._getWsEndpoint(endpoint, params);
|
|
405
|
+
}
|
|
406
|
+
// Internal interface to returning a WebSocket URL endpoint from the Protect controller for Protect API services (e.g. livestream, talkback).
|
|
407
|
+
async _getWsEndpoint(endpoint, params, retry = true) {
|
|
408
|
+
if (!endpoint) {
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
// Log us in if needed.
|
|
412
|
+
if (!(await this.loginController())) {
|
|
605
413
|
return null;
|
|
606
414
|
}
|
|
607
415
|
// Ask Protect to give us a URL for this websocket.
|
|
608
|
-
const response = await this.fetch(
|
|
416
|
+
const response = await this.fetch(this.getApiEndpoint("websocket") + "/" + endpoint + ((params && params.toString().length) ? "?" + params.toString() : ""));
|
|
609
417
|
// Something went wrong, we're done here.
|
|
610
|
-
if (!
|
|
611
|
-
|
|
418
|
+
if (!response?.ok) {
|
|
419
|
+
// Only inform users if we have a response if we have something to say.
|
|
420
|
+
if (response) {
|
|
421
|
+
this.log.error("API endpoint access error: %s - %s.%s", response.status.toString(), response.statusText, retry ? " Retrying." : "");
|
|
422
|
+
}
|
|
423
|
+
// We failed, but controllers are sometimes rebooted, we can lose our access token or something else may have occurred. Retry one time, after
|
|
424
|
+
// logging back in.
|
|
425
|
+
if (retry) {
|
|
426
|
+
this.clearLoginCredentials();
|
|
427
|
+
return this._getWsEndpoint(endpoint, params, false);
|
|
428
|
+
}
|
|
612
429
|
return null;
|
|
613
430
|
}
|
|
614
431
|
try {
|
|
@@ -620,70 +437,76 @@ class ProtectApi {
|
|
|
620
437
|
return responseUrl.toString();
|
|
621
438
|
}
|
|
622
439
|
catch (error) {
|
|
623
|
-
if (error instanceof
|
|
440
|
+
if (error instanceof FetchError) {
|
|
624
441
|
switch (error.code) {
|
|
625
442
|
default:
|
|
626
|
-
this.log.error("
|
|
443
|
+
this.log.error("Unknown error while communicating with the controller: %s", error.message);
|
|
627
444
|
break;
|
|
628
445
|
}
|
|
629
446
|
}
|
|
630
447
|
else {
|
|
631
|
-
this.log.error("
|
|
448
|
+
this.log.error("An error occurred while communicating with the controller: %s.", error);
|
|
632
449
|
}
|
|
633
450
|
return null;
|
|
634
451
|
}
|
|
635
452
|
}
|
|
636
453
|
// Utility to let us streamline error handling and return checking from the Protect API.
|
|
637
454
|
async fetch(url, options = { method: "GET" }, logErrors = true, decodeResponse = true, isRetry = false) {
|
|
455
|
+
const logError = (message, ...parameters) => this.log.error(message, ...parameters);
|
|
638
456
|
let response;
|
|
639
|
-
const controller = new
|
|
457
|
+
const controller = new AbortController();
|
|
640
458
|
// Ensure API responsiveness and guard against hung connections.
|
|
641
459
|
const timeout = setTimeout(() => {
|
|
642
460
|
controller.abort();
|
|
643
|
-
}, 1000 *
|
|
461
|
+
}, 1000 * PROTECT_API_TIMEOUT);
|
|
644
462
|
options.agent = this.httpsAgent;
|
|
645
463
|
options.headers = this.headers;
|
|
646
464
|
options.signal = controller.signal;
|
|
647
465
|
try {
|
|
648
466
|
const now = Date.now();
|
|
649
467
|
// Throttle this after PROTECT_API_ERROR_LIMIT attempts.
|
|
650
|
-
if (this.apiErrorCount >=
|
|
468
|
+
if (this.apiErrorCount >= PROTECT_API_ERROR_LIMIT) {
|
|
651
469
|
// Let the user know we've got an API problem.
|
|
652
|
-
if (this.apiErrorCount ===
|
|
653
|
-
|
|
470
|
+
if (this.apiErrorCount === PROTECT_API_ERROR_LIMIT) {
|
|
471
|
+
logError("Throttling API calls due to errors with the %s previous attempts. Pausing communication with the Protect controller for %s minutes.", this.apiErrorCount, PROTECT_API_RETRY_INTERVAL / 60);
|
|
654
472
|
this.apiErrorCount++;
|
|
655
473
|
this.apiLastSuccess = now;
|
|
656
474
|
return null;
|
|
657
475
|
}
|
|
658
|
-
//
|
|
659
|
-
if ((this.apiLastSuccess + (
|
|
476
|
+
// Check to see if we are still throttling our API calls.
|
|
477
|
+
if ((this.apiLastSuccess + (PROTECT_API_RETRY_INTERVAL * 1000)) > now) {
|
|
660
478
|
return null;
|
|
661
479
|
}
|
|
662
480
|
// Inform the user that we're out of the penalty box and try again.
|
|
663
|
-
|
|
481
|
+
logError("Resuming connectivity to the UniFi Protect API after pausing for %s minutes.", PROTECT_API_RETRY_INTERVAL / 60);
|
|
664
482
|
this.apiErrorCount = 0;
|
|
483
|
+
this.clearLoginCredentials();
|
|
484
|
+
if (!(await this.loginController())) {
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
665
487
|
}
|
|
666
|
-
response = await (
|
|
488
|
+
response = await fetch(url, options);
|
|
667
489
|
// The caller will sort through responses instead of us.
|
|
668
490
|
if (!decodeResponse) {
|
|
669
491
|
return response;
|
|
670
492
|
}
|
|
671
493
|
// Bad username and password.
|
|
672
494
|
if (response.status === 401) {
|
|
673
|
-
this.
|
|
495
|
+
this.clearLoginCredentials();
|
|
674
496
|
this.apiErrorCount++;
|
|
497
|
+
logError("Invalid login credentials given. Please check your login and password.");
|
|
675
498
|
return null;
|
|
676
499
|
}
|
|
677
500
|
// Insufficient privileges.
|
|
678
501
|
if (response.status === 403) {
|
|
679
502
|
this.apiErrorCount++;
|
|
680
|
-
|
|
503
|
+
logError("Insufficient privileges for this user. Please check the roles assigned to this user and ensure it has sufficient privileges.");
|
|
681
504
|
return null;
|
|
682
505
|
}
|
|
683
506
|
// Some other unknown error occurred.
|
|
684
507
|
if (!response.ok) {
|
|
685
508
|
this.apiErrorCount++;
|
|
686
|
-
|
|
509
|
+
logError("%s - %s", response.status, response.statusText);
|
|
687
510
|
return null;
|
|
688
511
|
}
|
|
689
512
|
this.apiLastSuccess = Date.now();
|
|
@@ -692,30 +515,32 @@ class ProtectApi {
|
|
|
692
515
|
}
|
|
693
516
|
catch (error) {
|
|
694
517
|
this.apiErrorCount++;
|
|
695
|
-
if (error instanceof
|
|
696
|
-
|
|
518
|
+
if (error instanceof AbortError) {
|
|
519
|
+
logError("Protect controller is taking too long to respond to a request. This error can usually be safely ignored.");
|
|
520
|
+
logError("Original request was: %s", url);
|
|
697
521
|
return null;
|
|
698
522
|
}
|
|
699
|
-
if (error instanceof
|
|
523
|
+
if (error instanceof FetchError) {
|
|
700
524
|
switch (error.code) {
|
|
701
525
|
case "ECONNREFUSED":
|
|
702
|
-
|
|
526
|
+
logError("Connection refused.");
|
|
703
527
|
break;
|
|
704
528
|
case "ECONNRESET":
|
|
705
529
|
// Retry on connection reset, but no more than once.
|
|
706
530
|
if (!isRetry) {
|
|
707
|
-
this.log.error("%s: Connection has been reset. Retrying the API action.", this.getNvrName());
|
|
708
531
|
return this.fetch(url, options, logErrors, decodeResponse, true);
|
|
709
532
|
}
|
|
710
|
-
|
|
533
|
+
logError("Network connection to Protect controller has been reset.");
|
|
711
534
|
break;
|
|
712
535
|
case "ENOTFOUND":
|
|
713
|
-
|
|
536
|
+
logError("Hostname or IP address not found: %s. Please ensure the address you configured for this UniFi Protect controller is correct.", this.nvrAddress);
|
|
714
537
|
break;
|
|
715
538
|
default:
|
|
539
|
+
// If we're logging when we have an error, do so.
|
|
716
540
|
if (logErrors) {
|
|
717
|
-
|
|
541
|
+
logError(error.message);
|
|
718
542
|
}
|
|
543
|
+
break;
|
|
719
544
|
}
|
|
720
545
|
}
|
|
721
546
|
return null;
|
|
@@ -725,6 +550,69 @@ class ProtectApi {
|
|
|
725
550
|
clearTimeout(timeout);
|
|
726
551
|
}
|
|
727
552
|
}
|
|
553
|
+
// Create a new livestream API instance.
|
|
554
|
+
createLivestream() {
|
|
555
|
+
return new ProtectLivestream(this);
|
|
556
|
+
}
|
|
557
|
+
// Return the appropriate URL to access various Protect API endpoints.
|
|
558
|
+
getApiEndpoint(deviceType) {
|
|
559
|
+
let endpointSuffix;
|
|
560
|
+
let endpointPrefix = "/proxy/protect/api/";
|
|
561
|
+
switch (deviceType) {
|
|
562
|
+
case "bootstrap":
|
|
563
|
+
endpointSuffix = "bootstrap";
|
|
564
|
+
break;
|
|
565
|
+
case "camera":
|
|
566
|
+
endpointSuffix = "cameras";
|
|
567
|
+
break;
|
|
568
|
+
case "light":
|
|
569
|
+
endpointSuffix = "lights";
|
|
570
|
+
break;
|
|
571
|
+
case "login":
|
|
572
|
+
endpointPrefix = "/api/";
|
|
573
|
+
endpointSuffix = "auth/login";
|
|
574
|
+
break;
|
|
575
|
+
case "nvr":
|
|
576
|
+
endpointSuffix = "nvr";
|
|
577
|
+
break;
|
|
578
|
+
case "self":
|
|
579
|
+
endpointPrefix = "/api/";
|
|
580
|
+
endpointSuffix = "users/self";
|
|
581
|
+
break;
|
|
582
|
+
case "sensor":
|
|
583
|
+
endpointSuffix = "sensors";
|
|
584
|
+
break;
|
|
585
|
+
case "websocket":
|
|
586
|
+
endpointSuffix = "ws";
|
|
587
|
+
break;
|
|
588
|
+
case "viewer":
|
|
589
|
+
endpointSuffix = "viewers";
|
|
590
|
+
break;
|
|
591
|
+
default:
|
|
592
|
+
break;
|
|
593
|
+
}
|
|
594
|
+
if (!endpointSuffix) {
|
|
595
|
+
return "";
|
|
596
|
+
}
|
|
597
|
+
return "https://" + this.nvrAddress + endpointPrefix + endpointSuffix;
|
|
598
|
+
}
|
|
599
|
+
// Get the bootstrap JSON.
|
|
600
|
+
get bootstrap() {
|
|
601
|
+
return this._bootstrap;
|
|
602
|
+
}
|
|
603
|
+
// Utility to access the logging functions, used by other classes in this library.
|
|
604
|
+
get log() {
|
|
605
|
+
return this._log;
|
|
606
|
+
}
|
|
607
|
+
// Utility to generate a nicely formatted NVR string.
|
|
608
|
+
get name() {
|
|
609
|
+
// Our NVR string, if it exists, appears as `NVR [NVR Type]`. Otherwise, we appear as `NVRaddress`.
|
|
610
|
+
if (this.bootstrap?.nvr) {
|
|
611
|
+
return this.bootstrap.nvr.name + " [" + this.bootstrap.nvr.type + "]";
|
|
612
|
+
}
|
|
613
|
+
else {
|
|
614
|
+
return this.nvrAddress;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
728
617
|
}
|
|
729
|
-
exports.ProtectApi = ProtectApi;
|
|
730
618
|
//# sourceMappingURL=protect-api.js.map
|