unifi-protect 0.0.2 → 2.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 +16 -0
- package/README.md +159 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/dist/protect-api-updates.d.ts +2 -3
- package/dist/protect-api-updates.js.map +1 -1
- package/dist/protect-api.d.ts +4 -8
- package/dist/protect-api.js +48 -52
- package/dist/protect-api.js.map +1 -1
- package/dist/protect-logging.d.ts +6 -0
- package/dist/protect-logging.js +7 -0
- package/dist/protect-logging.js.map +1 -0
- package/dist/protect-types.d.ts +4 -22
- package/dist/settings.js +2 -2
- package/package.json +64 -12
- package/.eslintrc.json +0 -40
- package/dist/logging.d.ts +0 -10
- package/dist/logging.js +0 -3
- package/dist/logging.js.map +0 -1
- package/src/index.ts +0 -3
- package/src/logging.ts +0 -16
- package/src/protect-api-updates.ts +0 -226
- package/src/protect-api.ts +0 -727
- package/src/protect-types.ts +0 -502
- package/src/settings.ts +0 -20
- package/tsconfig.json +0 -25
package/src/protect-api.ts
DELETED
|
@@ -1,727 +0,0 @@
|
|
|
1
|
-
/* Copyright(C) 2021, HJD (https://github.com/hjdhjd). All rights reserved.
|
|
2
|
-
*
|
|
3
|
-
* protect-api.ts: Our UniFi Protect API implementation.
|
|
4
|
-
*/
|
|
5
|
-
import {
|
|
6
|
-
PROTECT_API_ERROR_LIMIT,
|
|
7
|
-
PROTECT_API_RETRY_INTERVAL,
|
|
8
|
-
PROTECT_API_TIMEOUT,
|
|
9
|
-
PROTECT_EVENTS_HEARTBEAT_INTERVAL,
|
|
10
|
-
PROTECT_LOGIN_REFRESH_INTERVAL
|
|
11
|
-
} from "./settings";
|
|
12
|
-
import {
|
|
13
|
-
ProtectCameraChannelConfigInterface,
|
|
14
|
-
ProtectCameraConfig,
|
|
15
|
-
ProtectCameraConfigInterface,
|
|
16
|
-
ProtectCameraConfigPayload,
|
|
17
|
-
ProtectNvrBootstrap,
|
|
18
|
-
ProtectNvrUserConfig
|
|
19
|
-
} from "./protect-types";
|
|
20
|
-
import fetch, { AbortError, FetchError, Headers, RequestInfo, RequestInit, Response } from "node-fetch";
|
|
21
|
-
import https, { Agent } from "https";
|
|
22
|
-
import { AbortController } from "abort-controller";
|
|
23
|
-
import { Logging } from "./logging";
|
|
24
|
-
import WebSocket from "ws";
|
|
25
|
-
import util from "util";
|
|
26
|
-
|
|
27
|
-
/*
|
|
28
|
-
* The UniFi Protect API is largely undocumented and has been reverse engineered mostly through
|
|
29
|
-
* the web interface, and trial and error.
|
|
30
|
-
*
|
|
31
|
-
* Here's how the UniFi Protect API works:
|
|
32
|
-
*
|
|
33
|
-
* 1. Login to the UniFi Protect NVR device and acquire security credentials for further calls to the API.
|
|
34
|
-
*
|
|
35
|
-
* 2. Enumerate the list of UniFi Protect devices by calling the bootstrap URL. This
|
|
36
|
-
* contains almost everything you would want to know about this particular UniFi Protect NVR
|
|
37
|
-
* installation.
|
|
38
|
-
*
|
|
39
|
-
* Those are the basics and gets us up and running.
|
|
40
|
-
*/
|
|
41
|
-
|
|
42
|
-
export class ProtectApi {
|
|
43
|
-
private apiErrorCount: number;
|
|
44
|
-
private apiLastSuccess: number;
|
|
45
|
-
public bootstrap!: ProtectNvrBootstrap | null;
|
|
46
|
-
public Cameras!: ProtectCameraConfig[] | undefined;
|
|
47
|
-
private debug: (message: string, ...parameters: unknown[]) => void;
|
|
48
|
-
private eventHeartbeatTimer!: NodeJS.Timeout;
|
|
49
|
-
public eventListener!: WebSocket | null;
|
|
50
|
-
public eventListenerConfigured!: boolean;
|
|
51
|
-
private headers!: Headers;
|
|
52
|
-
private httpsAgent!: Agent;
|
|
53
|
-
public isAdminUser!: boolean;
|
|
54
|
-
private log: Logging;
|
|
55
|
-
private loggedIn!: boolean;
|
|
56
|
-
private loginAge!: number;
|
|
57
|
-
private nvrAddress: string;
|
|
58
|
-
private password: string;
|
|
59
|
-
private username: string;
|
|
60
|
-
|
|
61
|
-
// Initialize this instance with our login information.
|
|
62
|
-
constructor(debug: (message: string, ...parameters: unknown[]) => void, log: Logging, nvrAddress: string, username: string, password: string) {
|
|
63
|
-
this.apiErrorCount = 0;
|
|
64
|
-
this.apiLastSuccess = 0;
|
|
65
|
-
this.debug = debug;
|
|
66
|
-
this.log = log;
|
|
67
|
-
this.nvrAddress = nvrAddress;
|
|
68
|
-
this.username = username;
|
|
69
|
-
this.password = password;
|
|
70
|
-
|
|
71
|
-
this.clearLoginCredentials();
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// Identify which NVR device type we're logging into and acquire a CSRF token if needed.
|
|
75
|
-
private async acquireToken(): Promise<boolean> {
|
|
76
|
-
|
|
77
|
-
// We only need to acquire a token if we aren't already logged in, or we don't already have a token,
|
|
78
|
-
// or don't know which device type we're on.
|
|
79
|
-
if (this.loggedIn || this.headers.has("X-CSRF-Token") || this.headers.has("Authorization")) {
|
|
80
|
-
return true;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// UniFi OS has cross-site request forgery protection built into it's web management UI.
|
|
84
|
-
// We use this fact to fingerprint it by connecting directly to the supplied NVR address
|
|
85
|
-
// and see ifing there's a CSRF token waiting for us.
|
|
86
|
-
const response = await this.fetch("https://" + this.nvrAddress, { method: "GET" }, false);
|
|
87
|
-
|
|
88
|
-
if (response?.ok) {
|
|
89
|
-
const csrfToken = response.headers.get("X-CSRF-Token");
|
|
90
|
-
|
|
91
|
-
// We found a token.
|
|
92
|
-
if (csrfToken) {
|
|
93
|
-
this.headers.set("X-CSRF-Token", csrfToken);
|
|
94
|
-
|
|
95
|
-
// UniFi OS has support for keepalive. Let's take advantage of that and reduce the workload on controllers.
|
|
96
|
-
this.httpsAgent = new https.Agent({ keepAlive: true, maxFreeSockets: 5, maxSockets: 10, rejectUnauthorized: false, timeout: 60 * 1000 });
|
|
97
|
-
return true;
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// Couldn't deduce what type of NVR device we were connecting to.
|
|
102
|
-
return false;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// Log into UniFi Protect.
|
|
106
|
-
private async login(): Promise<boolean> {
|
|
107
|
-
const now = Date.now();
|
|
108
|
-
|
|
109
|
-
// Is it time to renew our credentials?
|
|
110
|
-
if (now > (this.loginAge + (PROTECT_LOGIN_REFRESH_INTERVAL * 1000))) {
|
|
111
|
-
this.loggedIn = false;
|
|
112
|
-
this.headers = new Headers();
|
|
113
|
-
this.headers.set("Content-Type", "application/json");
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// If we're already logged in, and it's not time to renew our credentials, we're done.
|
|
117
|
-
if (this.loggedIn) {
|
|
118
|
-
return true;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// Make sure we have a token, or get one if needed.
|
|
122
|
-
if (!(await this.acquireToken())) {
|
|
123
|
-
return false;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// Log us in.
|
|
127
|
-
const response = await this.fetch(this.authUrl(), {
|
|
128
|
-
body: JSON.stringify({ password: this.password, username: this.username }),
|
|
129
|
-
method: "POST"
|
|
130
|
-
});
|
|
131
|
-
|
|
132
|
-
if (!response?.ok) {
|
|
133
|
-
return false;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// We're logged in.
|
|
137
|
-
this.loggedIn = true;
|
|
138
|
-
this.loginAge = now;
|
|
139
|
-
|
|
140
|
-
// Configure headers.
|
|
141
|
-
const csrfToken = response.headers.get("X-CSRF-Token");
|
|
142
|
-
const cookie = response.headers.get("Set-Cookie");
|
|
143
|
-
|
|
144
|
-
if (csrfToken && cookie && this.headers.has("X-CSRF-Token")) {
|
|
145
|
-
|
|
146
|
-
this.headers.set("Cookie", cookie);
|
|
147
|
-
this.headers.set("X-CSRF-Token", csrfToken);
|
|
148
|
-
return true;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
// Clear out our login credentials and reset for another try.
|
|
152
|
-
this.clearLoginCredentials();
|
|
153
|
-
|
|
154
|
-
return false;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// Get our UniFi Protect NVR configuration.
|
|
158
|
-
private async bootstrapProtect(): Promise<boolean> {
|
|
159
|
-
// Log us in if needed.
|
|
160
|
-
if (!(await this.login())) {
|
|
161
|
-
return false;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
const response = await this.fetch(this.bootstrapUrl(), { method: "GET" });
|
|
165
|
-
|
|
166
|
-
if (!response?.ok) {
|
|
167
|
-
this.log.error("%s: Unable to retrieve NVR configuration information from UniFi Protect. Will retry again later.",
|
|
168
|
-
this.getNvrName());
|
|
169
|
-
|
|
170
|
-
// Clear out our login credentials and reset for another try.
|
|
171
|
-
this.clearLoginCredentials();
|
|
172
|
-
return false;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
// Now let's get our NVR configuration information.
|
|
176
|
-
let data: ProtectNvrBootstrap | null = null;
|
|
177
|
-
|
|
178
|
-
try {
|
|
179
|
-
data = await response.json() as ProtectNvrBootstrap;
|
|
180
|
-
} catch (error) {
|
|
181
|
-
data = null;
|
|
182
|
-
this.log.error("%s: Unable to parse response from UniFi Protect. Will retry again later.", this.getNvrName());
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
// No camera information returned.
|
|
186
|
-
if (!data?.cameras) {
|
|
187
|
-
this.log.error("%s: Unable to retrieve camera information from UniFi Protect. Will retry again later.", this.getNvrName());
|
|
188
|
-
|
|
189
|
-
// Clear out our login credentials and reset for another try.
|
|
190
|
-
this.clearLoginCredentials();
|
|
191
|
-
return false;
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
// On launch, let the user know we made it.
|
|
195
|
-
const firstRun = this.bootstrap ? false : true;
|
|
196
|
-
this.bootstrap = data;
|
|
197
|
-
|
|
198
|
-
if (firstRun) {
|
|
199
|
-
this.log.info("%s: Connected to the Protect controller API (address: %s mac: %s).", this.getNvrName(), data.nvr.host, data.nvr.mac);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// Capture the bootstrap if we're debugging.
|
|
203
|
-
this.debug(util.inspect(this.bootstrap, { colors: true, depth: null, sorted: true }));
|
|
204
|
-
|
|
205
|
-
// Check for admin user privileges or role changes.
|
|
206
|
-
this.checkAdminUserStatus(firstRun);
|
|
207
|
-
|
|
208
|
-
// We're good. Now connect to the event listener API.
|
|
209
|
-
return this.launchUpdatesListener();
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
// Connect to the realtime update events API.
|
|
213
|
-
private async launchUpdatesListener(): Promise<boolean> {
|
|
214
|
-
|
|
215
|
-
// Log us in if needed.
|
|
216
|
-
if (!(await this.login())) {
|
|
217
|
-
return false;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// If we already have a listener, we're already all set.
|
|
221
|
-
if (this.eventListener) {
|
|
222
|
-
return true;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
const params = new URLSearchParams({ lastUpdateId: this.bootstrap?.lastUpdateId ?? "" });
|
|
226
|
-
|
|
227
|
-
this.debug("Update listener: %s", this.updatesUrl() + "?" + params.toString());
|
|
228
|
-
|
|
229
|
-
try {
|
|
230
|
-
const ws = new WebSocket(this.updatesUrl() + "?" + params.toString(), {
|
|
231
|
-
headers: {
|
|
232
|
-
Cookie: this.headers.get("Cookie") ?? ""
|
|
233
|
-
},
|
|
234
|
-
rejectUnauthorized: false
|
|
235
|
-
});
|
|
236
|
-
|
|
237
|
-
if (!ws) {
|
|
238
|
-
this.log.error("Unable to connect to the realtime update events API. Will retry again later.");
|
|
239
|
-
this.eventListener = null;
|
|
240
|
-
this.eventListenerConfigured = false;
|
|
241
|
-
return false;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
this.eventListener = ws;
|
|
245
|
-
|
|
246
|
-
// Setup our heartbeat to ensure we can revive our connection if needed.
|
|
247
|
-
this.eventListener.on("message", this.heartbeatEventListener.bind(this));
|
|
248
|
-
this.eventListener.on("open", this.heartbeatEventListener.bind(this));
|
|
249
|
-
this.eventListener.on("ping", this.heartbeatEventListener.bind(this));
|
|
250
|
-
this.eventListener.on("close", () => {
|
|
251
|
-
|
|
252
|
-
clearTimeout(this.eventHeartbeatTimer);
|
|
253
|
-
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
this.eventListener.on("error", (error) => {
|
|
257
|
-
|
|
258
|
-
// If we're closing before fully established it's because we're shutting down the API - ignore it.
|
|
259
|
-
if (error.message !== "WebSocket was closed before the connection was established") {
|
|
260
|
-
this.log.error("%s: %s", this.getNvrName(), error);
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
this.eventListener?.terminate();
|
|
264
|
-
this.eventListener = null;
|
|
265
|
-
this.eventListenerConfigured = false;
|
|
266
|
-
|
|
267
|
-
});
|
|
268
|
-
|
|
269
|
-
this.log.info("%s: Connected to the UniFi realtime update events API.", this.getNvrName());
|
|
270
|
-
} catch (error) {
|
|
271
|
-
this.log.error("%s: Error connecting to the realtime update events API: %s", this.getNvrName(), error);
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
return true;
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
// Get the list of UniFi Protect devices associated with a NVR.
|
|
278
|
-
public async refreshDevices(): Promise<boolean> {
|
|
279
|
-
// Refresh the configuration from the NVR.
|
|
280
|
-
if (!(await this.bootstrapProtect())) {
|
|
281
|
-
return false;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
this.debug(util.inspect(this.bootstrap, { colors: true, depth: null, sorted: true }));
|
|
285
|
-
|
|
286
|
-
const newDeviceList: ProtectCameraConfig[] | undefined = this.bootstrap?.cameras;
|
|
287
|
-
|
|
288
|
-
// Notify the user about any new devices that we've discovered.
|
|
289
|
-
if (newDeviceList) {
|
|
290
|
-
for (const newDevice of newDeviceList) {
|
|
291
|
-
// We already know about this device.
|
|
292
|
-
if (this.Cameras?.some((x: ProtectCameraConfig) => x.mac === newDevice.mac)) {
|
|
293
|
-
continue;
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
// We only want to discover managed devices.
|
|
297
|
-
if (!newDevice.isManaged) {
|
|
298
|
-
continue;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
// We've discovered a new device.
|
|
302
|
-
this.log.info("%s: Discovered %s: %s.",
|
|
303
|
-
this.getNvrName(), newDevice.modelKey, this.getDeviceName(newDevice, newDevice.name, true));
|
|
304
|
-
|
|
305
|
-
this.debug(util.inspect(newDevice, { colors: true, depth: null, sorted: true }));
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// Notify the user about any devices that have disappeared.
|
|
310
|
-
if (this.Cameras) {
|
|
311
|
-
for (const existingDevice of this.Cameras) {
|
|
312
|
-
|
|
313
|
-
// This device still is visible.
|
|
314
|
-
if (newDeviceList?.some((x: ProtectCameraConfig) => x.mac === existingDevice.mac)) {
|
|
315
|
-
continue;
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
// We've had a device disappear.
|
|
319
|
-
this.debug("%s: Detected %s removal.", this.getFullName(existingDevice), existingDevice.modelKey);
|
|
320
|
-
|
|
321
|
-
this.debug(util.inspect(existingDevice, { colors: true, depth: null, sorted: true }));
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
// Save the updated list of devices.
|
|
326
|
-
this.Cameras = newDeviceList;
|
|
327
|
-
return true;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
// Validate if all RTSP channels enabled on all cameras.
|
|
331
|
-
public isAllRtspConfigured(): boolean {
|
|
332
|
-
|
|
333
|
-
// Look for any cameras with any non-RTSP enabled channels.
|
|
334
|
-
return this.bootstrap?.cameras?.some(camera => camera.channels?.some(channel => !channel.isRtspEnabled)) ? true : false;
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
// Check admin privileges.
|
|
338
|
-
private checkAdminUserStatus(firstRun = false): boolean {
|
|
339
|
-
if (!this.bootstrap?.users) {
|
|
340
|
-
return false;
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
// Save our prior state so we can detect role changes without having to restart.
|
|
344
|
-
const oldAdminStatus = this.isAdminUser;
|
|
345
|
-
|
|
346
|
-
// Find this user.
|
|
347
|
-
const user = this.bootstrap?.users.find((x: ProtectNvrUserConfig) => x.id === this.bootstrap?.authUserId);
|
|
348
|
-
|
|
349
|
-
if (!user?.allPermissions) {
|
|
350
|
-
return false;
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
// Let's figure out this user's permissions.
|
|
354
|
-
let newAdminStatus = false;
|
|
355
|
-
for (const entry of user.allPermissions) {
|
|
356
|
-
// Each permission line exists as: permissiontype:permissions:scope.
|
|
357
|
-
const permType = entry.split(":");
|
|
358
|
-
|
|
359
|
-
// We only care about camera permissions.
|
|
360
|
-
if (permType[0] !== "camera") {
|
|
361
|
-
continue;
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
// Get the individual permissions.
|
|
365
|
-
const permissions = permType[1].split(",");
|
|
366
|
-
|
|
367
|
-
// We found our administrative privileges - we're done.
|
|
368
|
-
if (permissions.indexOf("write") !== -1) {
|
|
369
|
-
newAdminStatus = true;
|
|
370
|
-
break;
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
this.isAdminUser = newAdminStatus;
|
|
375
|
-
|
|
376
|
-
// Only admin users can activate RTSP streams. Inform the user on startup, or if we detect a role change.
|
|
377
|
-
if (firstRun && !this.isAdminUser) {
|
|
378
|
-
this.log.info("%s: The user '%s' requires the Administrator role in order to automatically configure camera RTSP streams.",
|
|
379
|
-
this.getNvrName(), this.username);
|
|
380
|
-
} else if (!firstRun && (oldAdminStatus !== this.isAdminUser)) {
|
|
381
|
-
this.log.info("%s: Detected a role change for user '%s': the Administrator role has been %s.",
|
|
382
|
-
this.getNvrName(), this.username, this.isAdminUser ? "enabled" : "disabled");
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
return true;
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
private async checkCameraState(device: ProtectCameraConfigInterface): Promise<boolean> {
|
|
389
|
-
// Log us in if needed.
|
|
390
|
-
if (!(await this.login())) {
|
|
391
|
-
return false;
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
// Only admin users can activate RTSP streams.
|
|
395
|
-
if (!this.isAdminUser) {
|
|
396
|
-
return false;
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
// At the moment, we only know about camera devices.
|
|
400
|
-
if (device.modelKey !== "camera") {
|
|
401
|
-
return false;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
return true;
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
// Enable RTSP stream support on an attached Protect device.
|
|
408
|
-
public async updateChannels(device: ProtectCameraConfigInterface): Promise<ProtectCameraConfig | null> {
|
|
409
|
-
if (!(await this.checkCameraState(device))) {
|
|
410
|
-
return null;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
// Update Protect with the new configuration.
|
|
414
|
-
const response = await this.fetch(this.camerasUrl() + "/" + device.id, {
|
|
415
|
-
body: JSON.stringify({ channels: device.channels }),
|
|
416
|
-
method: "PATCH"
|
|
417
|
-
}, true, false);
|
|
418
|
-
|
|
419
|
-
// Since we took responsibility for interpreting the outcome of the fetch, we need to check for
|
|
420
|
-
// errors for ourself.
|
|
421
|
-
if (!response || !response?.ok) {
|
|
422
|
-
this.apiErrorCount++;
|
|
423
|
-
|
|
424
|
-
if (response?.status === 403) {
|
|
425
|
-
this.log.error("%s: Insufficient privileges to enable RTSP on all channels. Please ensure this username has the Administrator role assigned in UniFi Protect.",
|
|
426
|
-
this.getFullName(device));
|
|
427
|
-
} else {
|
|
428
|
-
this.log.error("%s: Unable to enable RTSP on all channels: %s.", this.getFullName(device), response?.status);
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
// We still return our camera object if there is at least one RTSP channel enabled.
|
|
432
|
-
return device;
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
// Since we have taken responsibility for decoding response types, we need to reset our API backoff count.
|
|
436
|
-
this.apiErrorCount = 0;
|
|
437
|
-
this.apiLastSuccess = Date.now();
|
|
438
|
-
|
|
439
|
-
// Everything worked, save the new channel array.
|
|
440
|
-
return await response.json() as ProtectCameraConfig;
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
// Enable RTSP stream support on an attached Protect device.
|
|
444
|
-
public async enableRtsp(device: ProtectCameraConfigInterface): Promise<ProtectCameraConfig | null> {
|
|
445
|
-
if (!(await this.checkCameraState(device))) {
|
|
446
|
-
return null;
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
// Do we have any non-RTSP enabled channels? If not, we're done.
|
|
450
|
-
if (!device.channels?.some(channel => !channel.isRtspEnabled)) {
|
|
451
|
-
return device;
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
// Enable RTSP on all available channels.
|
|
455
|
-
device.channels = device.channels.map((channel: ProtectCameraChannelConfigInterface) => {
|
|
456
|
-
channel.isRtspEnabled = true;
|
|
457
|
-
return channel;
|
|
458
|
-
});
|
|
459
|
-
|
|
460
|
-
return this.updateChannels(device);
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
// Update a camera object.
|
|
464
|
-
public async updateCamera(device: ProtectCameraConfig, payload: ProtectCameraConfigPayload): Promise<ProtectCameraConfig | null> {
|
|
465
|
-
|
|
466
|
-
// No device object, we're done.
|
|
467
|
-
if (!device) {
|
|
468
|
-
return null;
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
// Log us in if needed.
|
|
472
|
-
if (!(await this.login())) {
|
|
473
|
-
return null;
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
// Only admin users can show messages on doorbells.
|
|
477
|
-
if (!this.isAdminUser) {
|
|
478
|
-
return null;
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
this.debug("%s: %s", this.getFullName(device), util.inspect(payload, { colors: true, depth: null, sorted: true }));
|
|
482
|
-
|
|
483
|
-
// Update Protect with the new configuration.
|
|
484
|
-
const response = await this.fetch(this.camerasUrl() + "/" + device.id, {
|
|
485
|
-
body: JSON.stringify(payload),
|
|
486
|
-
method: "PATCH"
|
|
487
|
-
});
|
|
488
|
-
|
|
489
|
-
if (!response?.ok) {
|
|
490
|
-
this.log.error("%s: Unable to configure the camera: %s.", this.getFullName(device), response?.status);
|
|
491
|
-
return null;
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
// We successfully set the message, return the updated device object.
|
|
495
|
-
return await response.json() as ProtectCameraConfig;
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
// Utility to generate a nicely formatted NVR string.
|
|
499
|
-
public getNvrName(): string {
|
|
500
|
-
|
|
501
|
-
// Our NVR string, if it exists, appears as:
|
|
502
|
-
// NVR [NVR Type].
|
|
503
|
-
// Otherwise, we appear as NVRaddress.
|
|
504
|
-
if (this.bootstrap?.nvr) {
|
|
505
|
-
return this.bootstrap.nvr.name + " [" + this.bootstrap.nvr.type + "]";
|
|
506
|
-
} else {
|
|
507
|
-
return this.nvrAddress;
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
// Utility to generate a nicely formatted device string.
|
|
512
|
-
public getDeviceName(camera: ProtectCameraConfig, name = camera?.name, cameraInfo = false): string {
|
|
513
|
-
|
|
514
|
-
// Validate our inputs.
|
|
515
|
-
if (!camera) {
|
|
516
|
-
return "";
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
// A completely enumerated device will appear as:
|
|
520
|
-
// Camera [Camera Type] (address: IP address, mac: MAC address).
|
|
521
|
-
return name + " [" + camera.type + "]" +
|
|
522
|
-
(cameraInfo ? " (address: " + camera.host + " mac: " + camera.mac + ")" : "");
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
// Utility to generate a nicely formatted NVR and device string.
|
|
526
|
-
public getFullName(camera: ProtectCameraConfig): string {
|
|
527
|
-
const cameraName = this.getDeviceName(camera);
|
|
528
|
-
|
|
529
|
-
// Returns: NVR [NVR Type] Camera [Camera Type]
|
|
530
|
-
return this.getNvrName() + (cameraName.length > 0 ? " " + cameraName : "");
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
// Return the URL to directly access cameras, adjusting for Protect NVR variants.
|
|
534
|
-
public camerasUrl(): string {
|
|
535
|
-
|
|
536
|
-
// Boostrapping a UniFi OS device is done through: https://protect-nvr-ip/proxy/protect/api/cameras/CAMERAID.
|
|
537
|
-
return "https://" + this.nvrAddress + "/proxy/protect/api/cameras";
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
// Return the right authentication URL, depending on which Protect NVR platform we are using.
|
|
541
|
-
private authUrl(): string {
|
|
542
|
-
|
|
543
|
-
// Authenticating a UniFi OS device is done through: https://protect-nvr-ip/api/auth/login.
|
|
544
|
-
return "https://" + this.nvrAddress + "/api/auth/login";
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
// Return the right bootstrap URL, depending on which Protect NVR platform we are using.
|
|
548
|
-
private bootstrapUrl(): string {
|
|
549
|
-
|
|
550
|
-
// Boostrapping a UniFi OS device is done through: https://protect-nvr-ip/proxy/protect/api/bootstrap.
|
|
551
|
-
return "https://" + this.nvrAddress + "/proxy/protect/api/bootstrap";
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
// Return the realtime system events API URL.
|
|
555
|
-
private systemUrl(): string {
|
|
556
|
-
|
|
557
|
-
return "wss://" + this.nvrAddress + "/api/ws/system";
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
// Return the realtime update events API URL.
|
|
561
|
-
private updatesUrl(): string {
|
|
562
|
-
|
|
563
|
-
return "wss://" + this.nvrAddress + "/proxy/protect/ws/updates";
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
// Utility to check the heartbeat of our listener.
|
|
567
|
-
private heartbeatEventListener(): void {
|
|
568
|
-
|
|
569
|
-
// Clear out our last timer and set a new one.
|
|
570
|
-
clearTimeout(this.eventHeartbeatTimer);
|
|
571
|
-
|
|
572
|
-
// We use terminate() to immediately destroy the connection, instead of close(), which waits for the close timer.
|
|
573
|
-
this.eventHeartbeatTimer = setTimeout(() => {
|
|
574
|
-
this.eventListener?.terminate();
|
|
575
|
-
this.eventListener = null;
|
|
576
|
-
this.eventListenerConfigured = false;
|
|
577
|
-
}, PROTECT_EVENTS_HEARTBEAT_INTERVAL * 1000);
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
// Utility to clear out old login credentials or attempts.
|
|
581
|
-
public clearLoginCredentials(): void {
|
|
582
|
-
this.isAdminUser = false;
|
|
583
|
-
this.loggedIn = false;
|
|
584
|
-
this.loginAge = 0;
|
|
585
|
-
this.bootstrap = null;
|
|
586
|
-
|
|
587
|
-
// Shutdown any event listeners, if we have them.
|
|
588
|
-
this.eventListener?.terminate();
|
|
589
|
-
this.eventListener = null;
|
|
590
|
-
this.eventListenerConfigured = false;
|
|
591
|
-
|
|
592
|
-
// Initialize the headers we need.
|
|
593
|
-
this.headers = new Headers();
|
|
594
|
-
this.headers.set("Content-Type", "application/json");
|
|
595
|
-
|
|
596
|
-
// We want the initial agent to be connection-agnostic, except for certificate validate since Protect uses self-signed certificates.
|
|
597
|
-
// and we want to disable TLS validation, at a minimum. We want to take advantage of the fact that it supports keepalives to reduce
|
|
598
|
-
// workloads, but we deal with that elsewhere in acquireToken.
|
|
599
|
-
this.httpsAgent?.destroy();
|
|
600
|
-
this.httpsAgent = new https.Agent({ rejectUnauthorized: false });
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
// Utility to let us streamline error handling and return checking from the Protect API.
|
|
604
|
-
public async loginFetch(url: RequestInfo, options: RequestInit = { method: "GET" }, logErrors = true, decodeResponse = true): Promise<Response | null> {
|
|
605
|
-
if (!(await this.login())) {
|
|
606
|
-
return null;
|
|
607
|
-
}
|
|
608
|
-
|
|
609
|
-
return this.fetch(url, options, logErrors, decodeResponse);
|
|
610
|
-
}
|
|
611
|
-
|
|
612
|
-
// Utility to let us streamline error handling and return checking from the Protect API.
|
|
613
|
-
public async fetch(url: RequestInfo, options: RequestInit = { method: "GET" }, logErrors = true, decodeResponse = true): Promise<Response | null> {
|
|
614
|
-
let response: Response;
|
|
615
|
-
|
|
616
|
-
const controller = new AbortController();
|
|
617
|
-
|
|
618
|
-
// Ensure API responsiveness and guard against hung connections.
|
|
619
|
-
const timeout = setTimeout(() => {
|
|
620
|
-
controller.abort();
|
|
621
|
-
}, 1000 * PROTECT_API_TIMEOUT);
|
|
622
|
-
|
|
623
|
-
options.agent = this.httpsAgent;
|
|
624
|
-
options.headers = this.headers;
|
|
625
|
-
options.signal = controller.signal;
|
|
626
|
-
|
|
627
|
-
try {
|
|
628
|
-
|
|
629
|
-
const now = Date.now();
|
|
630
|
-
|
|
631
|
-
// Throttle this after PROTECT_API_ERROR_LIMIT attempts.
|
|
632
|
-
if (this.apiErrorCount >= PROTECT_API_ERROR_LIMIT) {
|
|
633
|
-
|
|
634
|
-
// Let the user know we've got an API problem.
|
|
635
|
-
if (this.apiErrorCount === PROTECT_API_ERROR_LIMIT) {
|
|
636
|
-
|
|
637
|
-
this.log.info("%s: Throttling API calls due to errors with the %s previous attempts. I'll retry again in %s minutes.",
|
|
638
|
-
this.getNvrName(), this.apiErrorCount, PROTECT_API_RETRY_INTERVAL / 60);
|
|
639
|
-
this.apiErrorCount++;
|
|
640
|
-
this.apiLastSuccess = now;
|
|
641
|
-
return null;
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
// Throttle our API calls.
|
|
645
|
-
if ((this.apiLastSuccess + (PROTECT_API_RETRY_INTERVAL * 1000)) > now) {
|
|
646
|
-
return null;
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
// Inform the user that we're out of the penalty box and try again.
|
|
650
|
-
this.log.info("%s: Resuming connectivity to the UniFi Protect API after throttling for %s minutes.",
|
|
651
|
-
this.getNvrName(), PROTECT_API_RETRY_INTERVAL / 60);
|
|
652
|
-
this.apiErrorCount = 0;
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
response = await fetch(url, options);
|
|
656
|
-
|
|
657
|
-
// The caller will sort through responses instead of us.
|
|
658
|
-
if (!decodeResponse) {
|
|
659
|
-
return response;
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
// Bad username and password.
|
|
663
|
-
if (response.status === 401) {
|
|
664
|
-
this.log.error("Invalid login credentials given. Please check your login and password.");
|
|
665
|
-
this.apiErrorCount++;
|
|
666
|
-
return null;
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
// Insufficient privileges.
|
|
670
|
-
if (response.status === 403) {
|
|
671
|
-
this.apiErrorCount++;
|
|
672
|
-
this.log.error("Insufficient privileges for this user. Please check the roles assigned to this user and ensure it has sufficient privileges.");
|
|
673
|
-
return null;
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
// Some other unknown error occurred.
|
|
677
|
-
if (!response.ok) {
|
|
678
|
-
this.apiErrorCount++;
|
|
679
|
-
this.log.error("API access error: %s - %s", response.status, response.statusText);
|
|
680
|
-
return null;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
this.apiLastSuccess = Date.now();
|
|
684
|
-
this.apiErrorCount = 0;
|
|
685
|
-
return response;
|
|
686
|
-
|
|
687
|
-
} catch (error) {
|
|
688
|
-
|
|
689
|
-
this.apiErrorCount++;
|
|
690
|
-
|
|
691
|
-
if (error instanceof AbortError) {
|
|
692
|
-
this.log.error("%s: Controller API connection terminated because it was taking too long. This error can usually be safely ignored.", this.getNvrName());
|
|
693
|
-
return null;
|
|
694
|
-
}
|
|
695
|
-
|
|
696
|
-
if (error instanceof FetchError) {
|
|
697
|
-
|
|
698
|
-
switch (error.code) {
|
|
699
|
-
case "ECONNREFUSED":
|
|
700
|
-
this.log.error("%s: Controller API connection refused.", this.getNvrName());
|
|
701
|
-
break;
|
|
702
|
-
|
|
703
|
-
case "ECONNRESET":
|
|
704
|
-
this.log.error("%s: Controller API connection reset.", this.getNvrName());
|
|
705
|
-
break;
|
|
706
|
-
|
|
707
|
-
case "ENOTFOUND":
|
|
708
|
-
this.log.error("%s: Hostname or IP address not found. Please ensure the address you configured for this UniFi Protect controller is correct.",
|
|
709
|
-
this.getNvrName());
|
|
710
|
-
break;
|
|
711
|
-
|
|
712
|
-
default:
|
|
713
|
-
if (logErrors) {
|
|
714
|
-
this.log.error(error.message);
|
|
715
|
-
}
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
return null;
|
|
720
|
-
|
|
721
|
-
} finally {
|
|
722
|
-
|
|
723
|
-
// Clear out our response timeout if needed.
|
|
724
|
-
clearTimeout(timeout);
|
|
725
|
-
}
|
|
726
|
-
}
|
|
727
|
-
}
|