unifi-protect 0.0.5 → 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 +5 -11
- package/dist/protect-api.js +62 -71
- 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 +3 -22
- package/dist/settings.d.ts +1 -1
- package/dist/settings.js +4 -4
- package/dist/settings.js.map +1 -1
- package/package.json +64 -13
- 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 -731
- package/src/protect-types.ts +0 -503
- package/src/settings.ts +0 -20
- package/tsconfig.json +0 -25
package/LICENSE.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
Internet Systems Consortium license
|
|
2
|
+
===================================
|
|
3
|
+
|
|
4
|
+
Copyright (c) `2017-2022`, `HJD https://github.com/hjdhjd`
|
|
5
|
+
|
|
6
|
+
Permission to use, copy, modify, and/or distribute this software for any purpose
|
|
7
|
+
with or without fee is hereby granted, provided that the above copyright notice
|
|
8
|
+
and this permission notice appear in all copies.
|
|
9
|
+
|
|
10
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
11
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
|
12
|
+
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
13
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
|
|
14
|
+
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
|
15
|
+
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
|
16
|
+
THIS SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,160 @@
|
|
|
1
|
-
|
|
1
|
+
<SPAN ALIGN="CENTER" STYLE="text-align:center">
|
|
2
|
+
<DIV ALIGN="CENTER" STYLE="text-align:center">
|
|
2
3
|
|
|
3
|
-
|
|
4
|
+
[](https://github.com/hjdhjd/unifi-protect)
|
|
5
|
+
|
|
6
|
+
# UniFi Protect API
|
|
7
|
+
|
|
8
|
+
[](https://www.npmjs.com/package/unifi-protect)
|
|
9
|
+
[](https://www.npmjs.com/package/unifi-protect)
|
|
10
|
+
|
|
11
|
+
## A complete UniFi Protect API implementation.
|
|
12
|
+
</DIV>
|
|
13
|
+
</SPAN>
|
|
14
|
+
|
|
15
|
+
`unifi-protect` is a library that enabled you to connect to and communicate with the Ubiquiti UniFi Protect API and ecosystem. [UniFi Protect](https://ui.com/camera-security) is [Ubiquiti's](https://www.ui.com) next-generation video security platform, with rich camera, doorbell, and NVR controller hardware options for you to choose from, as well as an app which you can use to view, configure and manage your video camera and doorbells.
|
|
16
|
+
|
|
17
|
+
## Why use this library for UniFi Protect support?
|
|
18
|
+
In short - because I use it every day to support a very popular [Homebridge](https://homebridge.io) plugin named [homebridge-unifi-protect](https://www.npmjs.com/package/homebridge-unifi-protect) that I maintain. I have been occasionally asked if I would consider packaging the core API library separately from the plugin so that other open source projects can take advantage of the work that's been done here to understand and decode the UniFi Protect API.
|
|
19
|
+
|
|
20
|
+
In addition, this implementation is unique: it's the first complete open source implementation of the realtime UniFi Protect update API, enabling instantaneous updates to Protect-related events.
|
|
21
|
+
|
|
22
|
+
Finally - the most significant reason that you should use this library: it's very well-tested, it is modern, and most importantly, *it just works*. It's quite easy to add support for UniFi Protect in your project using this library, and you can rely on the fact that the code is used by a significant population of users out there who ensure its continued robustness.
|
|
23
|
+
|
|
24
|
+
### <A NAME="protect-contribute"></A>How you can contribute and make this library even better
|
|
25
|
+
This implementation is largely feature complete. I strive to add support for meaningful features to a broad groups of people in order to avoid any unnecessary cruft and technical debt that may accrue over time.
|
|
26
|
+
|
|
27
|
+
The UniFi Protect API is undocumented and implementing a library like this one is the result of many hours of trial and error as well as community support.
|
|
28
|
+
|
|
29
|
+
### Features
|
|
30
|
+
- Full access to the UniFi Protect NVR JSON.
|
|
31
|
+
- The ability to retrieve the JSON details, including status, of any supported UniFi Protect device.
|
|
32
|
+
- The ability to modify the Protect NVR JSON or Protect devices.
|
|
33
|
+
|
|
34
|
+
## Changelog
|
|
35
|
+
* [Changelog](https://github.com/hjdhjd/unifi-protect/blob/main/docs/Changelog.md): changes and release history of this library.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
To use this library in Node, install it from the command line:
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
npm install unifi-protect
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Documentation
|
|
45
|
+
|
|
46
|
+
If you'd like to see all this in action in a well-documented, real-world example, please take a good look at my [homebridge-unifi-protect](https://github.com/hjdhjd/homebridge-unifi-protect) project. It relies heavily on this library for the core functionality it provides.
|
|
47
|
+
|
|
48
|
+
### ProtectApi(nvrAddress: string, username: string, password: string [, log: protectLogging])
|
|
49
|
+
Initialize the UniFi Protect API using the UniFi Protect account information contained in `username` and `password`. `log` is an optional parameter that enables you to customize the type of logging that can be generated, including debug logging. If `log` isn't specified, the Protect API will default to logging to the console.
|
|
50
|
+
|
|
51
|
+
### refreshDevices()
|
|
52
|
+
This is where the magic happens. This function:
|
|
53
|
+
|
|
54
|
+
* Logs into the Protect API, if we don't already have an access token.
|
|
55
|
+
* If we do have an access token and it's nearly time to refresh it, it will do so.
|
|
56
|
+
* It then requests a refresh of the UniFi Protect NVR state which includes device information for all the Protect devices associated with that NVR. There are failsafes in place to ensure the Protect NVR doesn't get slammed with API requests causing potential performance issues with the NVR.
|
|
57
|
+
|
|
58
|
+
**Note: `refreshDevices()` must be called at least once after instantiating the API in order to populate the list of UniFi Protect devices associated with an account.**
|
|
59
|
+
|
|
60
|
+
Returns: `true` if successful, `false` otherwise.
|
|
61
|
+
|
|
62
|
+
### protectApi.Cameras[]
|
|
63
|
+
The `Cameras` property maintains the list of all known Protect devices. It is an array of `ProtectCameraConfig` objects, and you can look through [protect-types.ts](https://github.com/hjdhjd/unifi-protect/blob/main/src/protect-types.ts) for a sense of what's contained in a `ProtectCameraConfig` object.
|
|
64
|
+
|
|
65
|
+
This property is refreshed each time `refreshDevices()` is called.
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
### More to come...
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
## UniFi Protect Realtime Updates API
|
|
72
|
+
So...how does UniFi Protect provide realtime updates? On UniFi OS-based controllers, it uses a websocket called `updates`. This connection provides a realtime stream of health, status, and events that the cameras encounter - including motion events and doorbell ring events.
|
|
73
|
+
|
|
74
|
+
Reverse engineering the realtime updates API is a bit more difficult than the system events API because it's based on a binary protocol. The Protect system events API is a steady stream of JSONs published on all UniFi OS controllers over the `system` websocket. It's used by more than just UniFi Protect, which makes it interesting for future exploration.
|
|
75
|
+
|
|
76
|
+
The Protect realtime updates API, however, is a binary protocol published over the `updates` websocket, and until now has been undocumented. I spent time analyzing what's happening in the Protect browser webUI as well as observing the controller and various Protect versions themselves to reverse engineer what's going on. Pouring through obfuscated code is like solving a puzzle with all the pieces in front of you - you know it's all there, you're just not always sure how it fits together.
|
|
77
|
+
|
|
78
|
+
For the impatient, you can take a look at the code for how to decode and read the binary protocol here in [protect-updates-api.ts](https://github.com/hjdhjd/unifi-protect/blob/master/src/protect-api-updates.ts) and the interface information located in [protect-types.ts](https://github.com/hjdhjd/unifi-protect/blob/master/src/protect-types.ts) as well.
|
|
79
|
+
|
|
80
|
+
I welcome any additions or corrections to the protocol for the benefit of the community. I hope this helps others launch their own exploration and create new and interesting Protect-enabled capabilities.
|
|
81
|
+
|
|
82
|
+
#### Non-Ubiquiti Apps Using the Protect API
|
|
83
|
+
This list represents all known apps that are using the realtime updates API for UniFi Protect. If you're using the information you discovered on this page for your own UniFi Protect-based solution, please open an issue and I'm happy to add a link to it below. I hope this can serve as a repository of sorts for UniFi Protect-based apps and solutions in the community.
|
|
84
|
+
|
|
85
|
+
* [homebridge-unifi-protect](https://github.com/hjdhjd/homebridge-unifi-protect): Seamless integration of UniFi Protect into HomeKit with support for cameras, doorbells, and more.
|
|
86
|
+
|
|
87
|
+
#### Connecting
|
|
88
|
+
* Login to the UniFi Protect controller and obtain the bootstrap JSON. The URL is: `https://protect-nvr-ip/proxy/protect/api/bootstrap`. You can look through [protect-api.ts](https://github.com/hjdhjd/unifi-protect/blob/master/src/protect-api.ts) for a better understanding of the Protect login process and how to obtain the bootstrap JSON.
|
|
89
|
+
* Open the websocket to the updates URL. The URL is: `wss://protect-nvr-ip/proxy/protect/ws/updates?lastUpdateId?lastUpdateId=X`. You can grab lastUpdateId from the bootstrap JSON in the prior step. You can [see an example in protect-api.ts](https://github.com/hjdhjd/unifi-protect/blob/src/protect-api.ts#L225).
|
|
90
|
+
* Then you're ready to listen to messages. You can see an [example of this in protect-nvr.ts](https://github.com/hjdhjd/unifi-protect/blob/src/protect-nvr.ts#L408).
|
|
91
|
+
|
|
92
|
+
Those are the basics and gets us up and running. Now, to explain how the updates API works...
|
|
93
|
+
|
|
94
|
+
#### Updates Websocket Binary Format
|
|
95
|
+
UniFi OS update data packets are used to provide a realtime stream of updates to Protect. It differs from the system events API in that the system events API appears to be shared across other applications (Network, Access, etc.) while the updates events API appears to only be utilized by Protect and not shared by other applications, although the protocol is shared.
|
|
96
|
+
|
|
97
|
+
The `updates` websocket is used by the UniFi Protect webUI and native applications to provide realtime updates back to the controller. UniFi cameras and doorbells also use a websocket to provide those same updates to the Protect controller. The `updates` websocket uses a binary protocol to encode data largely to minimize bandwidth requirements, and provide access to more than JSON data, if needed.
|
|
98
|
+
|
|
99
|
+
So how does it all work? Cameras continuously stream updates to the UniFi Protect controller containing things like camera health, statistics, and - crucially for us - events such as motion and doorbell ring. A complete update packet is composed of four frames:
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
Header Frame (8 bytes)
|
|
103
|
+
----------------------
|
|
104
|
+
Action Frame
|
|
105
|
+
----------------------
|
|
106
|
+
Header Frame (8 bytes)
|
|
107
|
+
----------------------
|
|
108
|
+
Data Frame
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Let's look at each of these.
|
|
112
|
+
|
|
113
|
+
##### Header Frame
|
|
114
|
+
The header frame is required overhead since websockets provide only a transport medium. It's purpose is to tell us what's coming in the frame that follows.
|
|
115
|
+
|
|
116
|
+
A packet header is composed of 8 bytes in this order:
|
|
117
|
+
|
|
118
|
+
| Byte Offset | Description | Bits | Values
|
|
119
|
+
|----------------|-----------------|---------|-----------------------------------------
|
|
120
|
+
| 0 | Packet Type | 8 | 1 - action frame, 2 - payload frame.
|
|
121
|
+
| 1 | Payload Format | 8 | 1 - JSON object, 2 - UTF8-encoded string, 3 - Node Buffer.
|
|
122
|
+
| 2 | Deflated | 8 | 0 - uncompressed, 1 - deflated / compressed ([zlib](https://nodejs.org/api/zlib.html)-based).
|
|
123
|
+
| 3 | Unknown | 8 | Always 0. Possibly reserved for future use by Ubiquiti?
|
|
124
|
+
| 4-7 | Payload Size | 32 | Size of payload in network-byte order (big endian).
|
|
125
|
+
|
|
126
|
+
If the header has marked the payload as deflated (compressed), you'll need to inflate (uncompress) the payload before you can use it.
|
|
127
|
+
|
|
128
|
+
##### Action Frame
|
|
129
|
+
The action frame identifies what the action and category that the update contains:
|
|
130
|
+
|
|
131
|
+
| Property | Description
|
|
132
|
+
|-------------|------------------------------------------------------------------------------------
|
|
133
|
+
| action | What action is being taken. Known actions are `add` and `update`.
|
|
134
|
+
| id | The identifier for the device we're updating.
|
|
135
|
+
| modelKey | The device model category that we're updating.
|
|
136
|
+
| newUpdateId | A new UUID generated on a per-update basis. This can be safely ignored it seems.
|
|
137
|
+
|
|
138
|
+
##### Data Frame
|
|
139
|
+
The final part of the update packet is the data frame. The data frame can be three different types of data - although in practice, JSONs are all that come across, I've found. Those types are:
|
|
140
|
+
|
|
141
|
+
| Payload Type | Description
|
|
142
|
+
|--------------|------------------------------------------------------------------------------------
|
|
143
|
+
| 1 | JSON. If the action frame's `action` property is set to `update` and the `modelKey` property is not set to `event` (e.g. `camera`), this will **always** a subset of the [configuration bootstrap JSON](https://github.com/hjdhjd/unifi-protect/blob/src/protect-types.ts#L6).
|
|
144
|
+
| 2 | A UTF8-encoded string.
|
|
145
|
+
| 3 | Node Buffer.
|
|
146
|
+
|
|
147
|
+
#### Tips
|
|
148
|
+
* `update` actions are always tied to any valid modelKey that exists in the bootstrap JSON. The exception is `events` which is tied to the Protect events history list that it maintains. The supported modelKeys from the bootstrap JSON are: `bridge`, `camera`, `group`, `light`, `liveview`, `nvr`, `sensor`, `user`, and `viewer`.
|
|
149
|
+
* `add` actions are always tied to the `event` modelKey and indicate the beginning of an event item in the Protect events list. A subsequent `update` action is sent signaling the end of the event capture, and it's confidence score for motion detection.
|
|
150
|
+
* This is **not** the same thing as motion detection. If you want to detect motion, you should watch the `update` action for `camera` modelKeys, and look for a JSON that updates `lastMotion`. For doorbell rings, `lastRing`. The Protect events list is useful for the Protect app, but it's of limited utility to HomeKit, and it's slow relative to just looking for the `lastMotion` JSON that tends to be much more timely in its delivery. If you want true realtime updates, you want to look at the `update` action.
|
|
151
|
+
* JSONs are only payload type that seems to be sent, although the protocol is designed to accept all three.
|
|
152
|
+
* With the exception of `update` actions with a `modelKey` of `event`, JSONs are always a subset of the bootstrap JSON, indexed off of `modelKey`. So for a `modelKey` of `camera`, the data payload is always a subset of ProtectCameraConfigInterface (see [protect-types.ts](https://github.com/hjdhjd/unifi-protect/blob/src/protect-types.ts#L108)).
|
|
153
|
+
|
|
154
|
+
## Library Development Dashboard
|
|
155
|
+
This is mostly of interest to the true developer nerds amongst us.
|
|
156
|
+
|
|
157
|
+
[](https://github.com/hjdhjd/unifi-protect/blob/main/LICENSE.md)
|
|
158
|
+
[](https://github.com/hjdhjd/unifi-protect/actions?query=workflow%3A%22Continuous+Integration%22)
|
|
159
|
+
[](https://libraries.io/npm/@hjdhjd/uniti-protect)
|
|
160
|
+
[](https://github.com/hjdhjd/unifi-protect/commits/main)
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
/* Copyright(C) 2019-2022, HJD (https://github.com/hjdhjd). All rights reserved.
|
|
3
|
+
*
|
|
4
|
+
* index.ts: UniFi Protect API registration.
|
|
5
|
+
*/
|
|
2
6
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
7
|
if (k2 === undefined) k2 = k;
|
|
4
8
|
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
@@ -10,7 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
10
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
11
15
|
};
|
|
12
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.FetchError = void 0;
|
|
13
18
|
__exportStar(require("./protect-api"), exports);
|
|
14
|
-
__exportStar(require("./protect-types"), exports);
|
|
15
19
|
__exportStar(require("./protect-api-updates"), exports);
|
|
20
|
+
__exportStar(require("./protect-types"), exports);
|
|
21
|
+
var node_fetch_cjs_1 = require("node-fetch-cjs");
|
|
22
|
+
Object.defineProperty(exports, "FetchError", { enumerable: true, get: function () { return node_fetch_cjs_1.FetchError; } });
|
|
16
23
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;;;;;;;;AAEH,gDAA8B;AAC9B,wDAAsC;AACtC,kDAAgC;AAChC,iDAA4C;AAAnC,4GAAA,UAAU,OAAA"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
-
import { Logging } from "./logging";
|
|
3
2
|
import { ProtectCameraLcdMessagePayload } from "./protect-types";
|
|
3
|
+
import { protectLogging } from "./protect-logging";
|
|
4
4
|
declare type ProtectNvrUpdatePacket = {
|
|
5
5
|
action: ProtectNvrUpdateEventAction;
|
|
6
6
|
payload: Record<string, unknown> | string | Buffer;
|
|
@@ -26,11 +26,10 @@ export declare type ProtectNvrUpdatePayloadCameraUpdate = {
|
|
|
26
26
|
isMotionDetected: boolean;
|
|
27
27
|
lastMotion: number;
|
|
28
28
|
lastRing: number;
|
|
29
|
-
lastSeen: number;
|
|
30
29
|
lcdMessage: ProtectCameraLcdMessagePayload;
|
|
31
30
|
};
|
|
32
31
|
export declare class ProtectApiUpdates {
|
|
33
|
-
static decodeUpdatePacket(log:
|
|
32
|
+
static decodeUpdatePacket(log: protectLogging, packet: Buffer): ProtectNvrUpdatePacket | null;
|
|
34
33
|
private static decodeUpdateFrame;
|
|
35
34
|
}
|
|
36
35
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protect-api-updates.js","sourceRoot":"","sources":["../src/protect-api-updates.ts"],"names":[],"mappings":";;;;;;AAMA,gDAAwB;AAExB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+DG;AAEH,oDAAoD;AACpD,MAAM,yBAAyB,G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GED
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
import { ProtectCameraConfig, ProtectCameraConfigInterface, ProtectCameraConfigPayload, ProtectNvrBootstrap } from "./protect-types";
|
|
2
|
-
import { RequestInfo, RequestInit, Response } from "node-fetch";
|
|
3
|
-
import { Logging } from "./logging";
|
|
2
|
+
import { RequestInfo, RequestInit, Response } from "node-fetch-cjs";
|
|
4
3
|
import WebSocket from "ws";
|
|
4
|
+
import { protectLogging } from "./protect-logging";
|
|
5
5
|
export declare class ProtectApi {
|
|
6
|
-
disableKeepAlive?: boolean | undefined;
|
|
7
6
|
private apiErrorCount;
|
|
8
7
|
private apiLastSuccess;
|
|
9
8
|
bootstrap: ProtectNvrBootstrap | null;
|
|
10
9
|
Cameras: ProtectCameraConfig[] | undefined;
|
|
11
|
-
private debug;
|
|
12
10
|
private eventHeartbeatTimer;
|
|
13
11
|
eventListener: WebSocket | null;
|
|
14
12
|
eventListenerConfigured: boolean;
|
|
15
13
|
private headers;
|
|
14
|
+
private httpsAgent;
|
|
16
15
|
isAdminUser: boolean;
|
|
17
16
|
private log;
|
|
18
17
|
private loggedIn;
|
|
@@ -20,18 +19,14 @@ export declare class ProtectApi {
|
|
|
20
19
|
private nvrAddress;
|
|
21
20
|
private password;
|
|
22
21
|
private username;
|
|
23
|
-
|
|
24
|
-
constructor(debug: (message: string, ...parameters: unknown[]) => void, log: Logging, nvrAddress: string, username: string, password: string, disableKeepAlive?: boolean | undefined);
|
|
22
|
+
constructor(nvrAddress: string, username: string, password: string, log?: protectLogging);
|
|
25
23
|
private acquireToken;
|
|
26
|
-
private loginWrapped;
|
|
27
24
|
private login;
|
|
28
25
|
private bootstrapProtect;
|
|
29
26
|
private launchUpdatesListener;
|
|
30
27
|
refreshDevices(): Promise<boolean>;
|
|
31
28
|
isAllRtspConfigured(): boolean;
|
|
32
29
|
private checkAdminUserStatus;
|
|
33
|
-
private checkCameraState;
|
|
34
|
-
updateChannels(device: ProtectCameraConfigInterface): Promise<ProtectCameraConfig | null>;
|
|
35
30
|
enableRtsp(device: ProtectCameraConfigInterface): Promise<ProtectCameraConfig | null>;
|
|
36
31
|
updateCamera(device: ProtectCameraConfig, payload: ProtectCameraConfigPayload): Promise<ProtectCameraConfig | null>;
|
|
37
32
|
getNvrName(): string;
|
|
@@ -44,6 +39,5 @@ export declare class ProtectApi {
|
|
|
44
39
|
private updatesUrl;
|
|
45
40
|
private heartbeatEventListener;
|
|
46
41
|
clearLoginCredentials(): void;
|
|
47
|
-
|
|
48
|
-
fetch(url: RequestInfo, options?: RequestInit, logErrors?: boolean, decodeResponse?: boolean): Promise<Response | null>;
|
|
42
|
+
fetch(url: RequestInfo, options?: RequestInit, logErrors?: boolean, decodeResponse?: boolean, isRetry?: boolean): Promise<Response | null>;
|
|
49
43
|
}
|
package/dist/protect-api.js
CHANGED
|
@@ -23,17 +23,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
23
23
|
};
|
|
24
24
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
25
|
exports.ProtectApi = void 0;
|
|
26
|
-
/* Copyright(C)
|
|
26
|
+
/* Copyright(C) 2019-2022, HJD (https://github.com/hjdhjd). All rights reserved.
|
|
27
27
|
*
|
|
28
28
|
* protect-api.ts: Our UniFi Protect API implementation.
|
|
29
29
|
*/
|
|
30
30
|
const settings_1 = require("./settings");
|
|
31
|
-
const
|
|
31
|
+
const node_fetch_cjs_1 = __importStar(require("node-fetch-cjs"));
|
|
32
32
|
const https_1 = __importDefault(require("https"));
|
|
33
33
|
const abort_controller_1 = require("abort-controller");
|
|
34
34
|
const ws_1 = __importDefault(require("ws"));
|
|
35
35
|
const util_1 = __importDefault(require("util"));
|
|
36
|
-
const httpsAgent = new https_1.default.Agent({ rejectUnauthorized: false });
|
|
37
36
|
/*
|
|
38
37
|
* The UniFi Protect API is largely undocumented and has been reverse engineered mostly through
|
|
39
38
|
* the web interface, and trial and error.
|
|
@@ -46,15 +45,25 @@ const httpsAgent = new https_1.default.Agent({ rejectUnauthorized: false });
|
|
|
46
45
|
* contains almost everything you would want to know about this particular UniFi Protect NVR
|
|
47
46
|
* installation.
|
|
48
47
|
*
|
|
49
|
-
* Those are the basics
|
|
48
|
+
* Those are the basics that gets us up and running.
|
|
50
49
|
*/
|
|
51
50
|
class ProtectApi {
|
|
52
51
|
// Initialize this instance with our login information.
|
|
53
|
-
constructor(
|
|
54
|
-
|
|
52
|
+
constructor(nvrAddress, username, password, log) {
|
|
53
|
+
// If we didn't get passed a logging parameter, by default we log to the console.
|
|
54
|
+
if (!log) {
|
|
55
|
+
log = {
|
|
56
|
+
/* eslint-disable no-console */
|
|
57
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
58
|
+
debug: (message, ...parameters) => { },
|
|
59
|
+
error: (message, ...parameters) => console.error(util_1.default.format(message, ...parameters)),
|
|
60
|
+
info: (message, ...parameters) => console.log(util_1.default.format(message, ...parameters)),
|
|
61
|
+
warn: (message, ...parameters) => console.log(util_1.default.format(message, ...parameters))
|
|
62
|
+
/* eslint-enable no-console */
|
|
63
|
+
};
|
|
64
|
+
}
|
|
55
65
|
this.apiErrorCount = 0;
|
|
56
66
|
this.apiLastSuccess = 0;
|
|
57
|
-
this.debug = debug;
|
|
58
67
|
this.log = log;
|
|
59
68
|
this.nvrAddress = nvrAddress;
|
|
60
69
|
this.username = username;
|
|
@@ -77,6 +86,8 @@ class ProtectApi {
|
|
|
77
86
|
// We found a token.
|
|
78
87
|
if (csrfToken) {
|
|
79
88
|
this.headers.set("X-CSRF-Token", csrfToken);
|
|
89
|
+
// UniFi OS has support for keepalive. Let's take advantage of that and reduce the workload on controllers.
|
|
90
|
+
this.httpsAgent = new https_1.default.Agent({ keepAlive: true, maxFreeSockets: 5, maxSockets: 10, rejectUnauthorized: false, timeout: 60 * 1000 });
|
|
80
91
|
return true;
|
|
81
92
|
}
|
|
82
93
|
}
|
|
@@ -84,11 +95,13 @@ class ProtectApi {
|
|
|
84
95
|
return false;
|
|
85
96
|
}
|
|
86
97
|
// Log into UniFi Protect.
|
|
87
|
-
async
|
|
98
|
+
async login() {
|
|
88
99
|
const now = Date.now();
|
|
89
100
|
// Is it time to renew our credentials?
|
|
90
101
|
if (now > (this.loginAge + (settings_1.PROTECT_LOGIN_REFRESH_INTERVAL * 1000))) {
|
|
91
|
-
this.
|
|
102
|
+
this.loggedIn = false;
|
|
103
|
+
this.headers = new node_fetch_cjs_1.Headers();
|
|
104
|
+
this.headers.set("Content-Type", "application/json");
|
|
92
105
|
}
|
|
93
106
|
// If we're already logged in, and it's not time to renew our credentials, we're done.
|
|
94
107
|
if (this.loggedIn) {
|
|
@@ -96,7 +109,6 @@ class ProtectApi {
|
|
|
96
109
|
}
|
|
97
110
|
// Make sure we have a token, or get one if needed.
|
|
98
111
|
if (!(await this.acquireToken())) {
|
|
99
|
-
this.clearLoginCredentials();
|
|
100
112
|
return false;
|
|
101
113
|
}
|
|
102
114
|
// Log us in.
|
|
@@ -105,7 +117,6 @@ class ProtectApi {
|
|
|
105
117
|
method: "POST"
|
|
106
118
|
});
|
|
107
119
|
if (!(response === null || response === void 0 ? void 0 : response.ok)) {
|
|
108
|
-
this.clearLoginCredentials();
|
|
109
120
|
return false;
|
|
110
121
|
}
|
|
111
122
|
// We're logged in.
|
|
@@ -123,14 +134,6 @@ class ProtectApi {
|
|
|
123
134
|
this.clearLoginCredentials();
|
|
124
135
|
return false;
|
|
125
136
|
}
|
|
126
|
-
login() {
|
|
127
|
-
// coalesce multiple requests into a single login attempt.
|
|
128
|
-
if (!this.pendingLogin) {
|
|
129
|
-
this.pendingLogin = this.loginWrapped();
|
|
130
|
-
this.pendingLogin.finally(() => this.pendingLogin = undefined);
|
|
131
|
-
}
|
|
132
|
-
return this.pendingLogin;
|
|
133
|
-
}
|
|
134
137
|
// Get our UniFi Protect NVR configuration.
|
|
135
138
|
async bootstrapProtect() {
|
|
136
139
|
// Log us in if needed.
|
|
@@ -167,7 +170,7 @@ class ProtectApi {
|
|
|
167
170
|
this.log.info("%s: Connected to the Protect controller API (address: %s mac: %s).", this.getNvrName(), data.nvr.host, data.nvr.mac);
|
|
168
171
|
}
|
|
169
172
|
// Capture the bootstrap if we're debugging.
|
|
170
|
-
this.debug(util_1.default.inspect(this.bootstrap, { colors: true, depth: null, sorted: true }));
|
|
173
|
+
this.log.debug(util_1.default.inspect(this.bootstrap, { colors: true, depth: null, sorted: true }));
|
|
171
174
|
// Check for admin user privileges or role changes.
|
|
172
175
|
this.checkAdminUserStatus(firstRun);
|
|
173
176
|
// We're good. Now connect to the event listener API.
|
|
@@ -185,7 +188,7 @@ class ProtectApi {
|
|
|
185
188
|
return true;
|
|
186
189
|
}
|
|
187
190
|
const params = new URLSearchParams({ lastUpdateId: (_b = (_a = this.bootstrap) === null || _a === void 0 ? void 0 : _a.lastUpdateId) !== null && _b !== void 0 ? _b : "" });
|
|
188
|
-
this.debug("Update listener: %s", this.updatesUrl() + "?" + params.toString());
|
|
191
|
+
this.log.debug("Update listener: %s", this.updatesUrl() + "?" + params.toString());
|
|
189
192
|
try {
|
|
190
193
|
const ws = new ws_1.default(this.updatesUrl() + "?" + params.toString(), {
|
|
191
194
|
headers: {
|
|
@@ -231,7 +234,7 @@ class ProtectApi {
|
|
|
231
234
|
if (!(await this.bootstrapProtect())) {
|
|
232
235
|
return false;
|
|
233
236
|
}
|
|
234
|
-
this.debug(util_1.default.inspect(this.bootstrap, { colors: true, depth: null, sorted: true }));
|
|
237
|
+
this.log.debug(util_1.default.inspect(this.bootstrap, { colors: true, depth: null, sorted: true }));
|
|
235
238
|
const newDeviceList = (_a = this.bootstrap) === null || _a === void 0 ? void 0 : _a.cameras;
|
|
236
239
|
// Notify the user about any new devices that we've discovered.
|
|
237
240
|
if (newDeviceList) {
|
|
@@ -246,7 +249,7 @@ class ProtectApi {
|
|
|
246
249
|
}
|
|
247
250
|
// We've discovered a new device.
|
|
248
251
|
this.log.info("%s: Discovered %s: %s.", this.getNvrName(), newDevice.modelKey, this.getDeviceName(newDevice, newDevice.name, true));
|
|
249
|
-
this.debug(util_1.default.inspect(newDevice, { colors: true, depth: null, sorted: true }));
|
|
252
|
+
this.log.debug(util_1.default.inspect(newDevice, { colors: true, depth: null, sorted: true }));
|
|
250
253
|
}
|
|
251
254
|
}
|
|
252
255
|
// Notify the user about any devices that have disappeared.
|
|
@@ -257,8 +260,8 @@ class ProtectApi {
|
|
|
257
260
|
continue;
|
|
258
261
|
}
|
|
259
262
|
// We've had a device disappear.
|
|
260
|
-
this.debug("%s: Detected %s removal.", this.getFullName(existingDevice), existingDevice.modelKey);
|
|
261
|
-
this.debug(util_1.default.inspect(existingDevice, { colors: true, depth: null, sorted: true }));
|
|
263
|
+
this.log.debug("%s: Detected %s removal.", this.getFullName(existingDevice), existingDevice.modelKey);
|
|
264
|
+
this.log.debug(util_1.default.inspect(existingDevice, { colors: true, depth: null, sorted: true }));
|
|
262
265
|
}
|
|
263
266
|
}
|
|
264
267
|
// Save the updated list of devices.
|
|
@@ -311,26 +314,30 @@ class ProtectApi {
|
|
|
311
314
|
}
|
|
312
315
|
return true;
|
|
313
316
|
}
|
|
314
|
-
|
|
317
|
+
// Enable RTSP stream support on an attached Protect device.
|
|
318
|
+
async enableRtsp(device) {
|
|
319
|
+
var _a;
|
|
315
320
|
// Log us in if needed.
|
|
316
321
|
if (!(await this.login())) {
|
|
317
|
-
return
|
|
322
|
+
return null;
|
|
318
323
|
}
|
|
319
324
|
// Only admin users can activate RTSP streams.
|
|
320
325
|
if (!this.isAdminUser) {
|
|
321
|
-
return
|
|
326
|
+
return null;
|
|
322
327
|
}
|
|
323
328
|
// At the moment, we only know about camera devices.
|
|
324
329
|
if (device.modelKey !== "camera") {
|
|
325
|
-
return false;
|
|
326
|
-
}
|
|
327
|
-
return true;
|
|
328
|
-
}
|
|
329
|
-
// Enable RTSP stream support on an attached Protect device.
|
|
330
|
-
async updateChannels(device) {
|
|
331
|
-
if (!(await this.checkCameraState(device))) {
|
|
332
330
|
return null;
|
|
333
331
|
}
|
|
332
|
+
// Do we have any non-RTSP enabled channels? If not, we're done.
|
|
333
|
+
if (!((_a = device.channels) === null || _a === void 0 ? void 0 : _a.some(channel => !channel.isRtspEnabled))) {
|
|
334
|
+
return device;
|
|
335
|
+
}
|
|
336
|
+
// Enable RTSP on all available channels.
|
|
337
|
+
device.channels = device.channels.map((channel) => {
|
|
338
|
+
channel.isRtspEnabled = true;
|
|
339
|
+
return channel;
|
|
340
|
+
});
|
|
334
341
|
// Update Protect with the new configuration.
|
|
335
342
|
const response = await this.fetch(this.camerasUrl() + "/" + device.id, {
|
|
336
343
|
body: JSON.stringify({ channels: device.channels }),
|
|
@@ -355,23 +362,6 @@ class ProtectApi {
|
|
|
355
362
|
// Everything worked, save the new channel array.
|
|
356
363
|
return await response.json();
|
|
357
364
|
}
|
|
358
|
-
// Enable RTSP stream support on an attached Protect device.
|
|
359
|
-
async enableRtsp(device) {
|
|
360
|
-
var _a;
|
|
361
|
-
if (!(await this.checkCameraState(device))) {
|
|
362
|
-
return null;
|
|
363
|
-
}
|
|
364
|
-
// Do we have any non-RTSP enabled channels? If not, we're done.
|
|
365
|
-
if (!((_a = device.channels) === null || _a === void 0 ? void 0 : _a.some(channel => !channel.isRtspEnabled))) {
|
|
366
|
-
return device;
|
|
367
|
-
}
|
|
368
|
-
// Enable RTSP on all available channels.
|
|
369
|
-
device.channels = device.channels.map((channel) => {
|
|
370
|
-
channel.isRtspEnabled = true;
|
|
371
|
-
return channel;
|
|
372
|
-
});
|
|
373
|
-
return this.updateChannels(device);
|
|
374
|
-
}
|
|
375
365
|
// Update a camera object.
|
|
376
366
|
async updateCamera(device, payload) {
|
|
377
367
|
// No device object, we're done.
|
|
@@ -386,7 +376,7 @@ class ProtectApi {
|
|
|
386
376
|
if (!this.isAdminUser) {
|
|
387
377
|
return null;
|
|
388
378
|
}
|
|
389
|
-
this.debug("%s: %s", this.getFullName(device), util_1.default.inspect(payload, { colors: true, depth: null, sorted: true }));
|
|
379
|
+
this.log.debug("%s: %s", this.getFullName(device), util_1.default.inspect(payload, { colors: true, depth: null, sorted: true }));
|
|
390
380
|
// Update Protect with the new configuration.
|
|
391
381
|
const response = await this.fetch(this.camerasUrl() + "/" + device.id, {
|
|
392
382
|
body: JSON.stringify(payload),
|
|
@@ -466,7 +456,7 @@ class ProtectApi {
|
|
|
466
456
|
}
|
|
467
457
|
// Utility to clear out old login credentials or attempts.
|
|
468
458
|
clearLoginCredentials() {
|
|
469
|
-
var _a;
|
|
459
|
+
var _a, _b;
|
|
470
460
|
this.isAdminUser = false;
|
|
471
461
|
this.loggedIn = false;
|
|
472
462
|
this.loginAge = 0;
|
|
@@ -476,25 +466,23 @@ class ProtectApi {
|
|
|
476
466
|
this.eventListener = null;
|
|
477
467
|
this.eventListenerConfigured = false;
|
|
478
468
|
// Initialize the headers we need.
|
|
479
|
-
this.headers = new
|
|
469
|
+
this.headers = new node_fetch_cjs_1.Headers();
|
|
480
470
|
this.headers.set("Content-Type", "application/json");
|
|
471
|
+
// We want the initial agent to be connection-agnostic, except for certificate validate since Protect uses self-signed certificates.
|
|
472
|
+
// and we want to disable TLS validation, at a minimum. We want to take advantage of the fact that it supports keepalives to reduce
|
|
473
|
+
// workloads, but we deal with that elsewhere in acquireToken.
|
|
474
|
+
(_b = this.httpsAgent) === null || _b === void 0 ? void 0 : _b.destroy();
|
|
475
|
+
this.httpsAgent = new https_1.default.Agent({ rejectUnauthorized: false });
|
|
481
476
|
}
|
|
482
477
|
// Utility to let us streamline error handling and return checking from the Protect API.
|
|
483
|
-
async
|
|
484
|
-
if (!(await this.login())) {
|
|
485
|
-
return null;
|
|
486
|
-
}
|
|
487
|
-
return this.fetch(url, options, logErrors, decodeResponse);
|
|
488
|
-
}
|
|
489
|
-
// Utility to let us streamline error handling and return checking from the Protect API.
|
|
490
|
-
async fetch(url, options = { method: "GET" }, logErrors = true, decodeResponse = true) {
|
|
478
|
+
async fetch(url, options = { method: "GET" }, logErrors = true, decodeResponse = true, isRetry = false) {
|
|
491
479
|
let response;
|
|
492
480
|
const controller = new abort_controller_1.AbortController();
|
|
493
481
|
// Ensure API responsiveness and guard against hung connections.
|
|
494
482
|
const timeout = setTimeout(() => {
|
|
495
483
|
controller.abort();
|
|
496
484
|
}, 1000 * settings_1.PROTECT_API_TIMEOUT);
|
|
497
|
-
options.agent = httpsAgent;
|
|
485
|
+
options.agent = this.httpsAgent;
|
|
498
486
|
options.headers = this.headers;
|
|
499
487
|
options.signal = controller.signal;
|
|
500
488
|
try {
|
|
@@ -516,7 +504,7 @@ class ProtectApi {
|
|
|
516
504
|
this.log.info("%s: Resuming connectivity to the UniFi Protect API after throttling for %s minutes.", this.getNvrName(), settings_1.PROTECT_API_RETRY_INTERVAL / 60);
|
|
517
505
|
this.apiErrorCount = 0;
|
|
518
506
|
}
|
|
519
|
-
response = await
|
|
507
|
+
response = await (0, node_fetch_cjs_1.default)(url, options);
|
|
520
508
|
// The caller will sort through responses instead of us.
|
|
521
509
|
if (!decodeResponse) {
|
|
522
510
|
return response;
|
|
@@ -545,18 +533,21 @@ class ProtectApi {
|
|
|
545
533
|
}
|
|
546
534
|
catch (error) {
|
|
547
535
|
this.apiErrorCount++;
|
|
548
|
-
if (error instanceof
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
return null;
|
|
552
|
-
}
|
|
536
|
+
if (error instanceof node_fetch_cjs_1.AbortError) {
|
|
537
|
+
this.log.error("%s: Controller API connection terminated because it was taking too long. This error can usually be safely ignored.", this.getNvrName());
|
|
538
|
+
return null;
|
|
553
539
|
}
|
|
554
|
-
if (error instanceof
|
|
540
|
+
if (error instanceof node_fetch_cjs_1.FetchError) {
|
|
555
541
|
switch (error.code) {
|
|
556
542
|
case "ECONNREFUSED":
|
|
557
543
|
this.log.error("%s: Controller API connection refused.", this.getNvrName());
|
|
558
544
|
break;
|
|
559
545
|
case "ECONNRESET":
|
|
546
|
+
// Retry on connection reset, but no more than once.
|
|
547
|
+
if (!isRetry) {
|
|
548
|
+
this.log.error("%s: Connection has been reset. Retrying the API action.", this.getNvrName());
|
|
549
|
+
return this.fetch(url, options, logErrors, decodeResponse, true);
|
|
550
|
+
}
|
|
560
551
|
this.log.error("%s: Controller API connection reset.", this.getNvrName());
|
|
561
552
|
break;
|
|
562
553
|
case "ENOTFOUND":
|