unifi-protect 0.0.5 → 3.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 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,174 @@
1
- # unifi-protect
1
+ <SPAN ALIGN="CENTER" STYLE="text-align:center">
2
+ <DIV ALIGN="CENTER" STYLE="text-align:center">
2
3
 
3
- Unifi Protect API. Imported from https://github.com/hjdhjd/homebridge-unifi-protect.
4
+ [![unifi-protect: UniFi Protect API](https://raw.githubusercontent.com/hjdhjd/unifi-protect/main/unifi-protect-logo.svg)](https://github.com/hjdhjd/unifi-protect)
5
+
6
+ # UniFi Protect API
7
+
8
+ [![Downloads](https://img.shields.io/npm/dt/unifi-protect?color=%230559C9&logo=icloud&logoColor=%23FFFFFF&style=for-the-badge)](https://www.npmjs.com/package/unifi-protect)
9
+ [![Version](https://img.shields.io/npm/v/unifi-protect?color=%230559C9&label=UniFi%20Protect%20API&logo=ubiquiti&logoColor=%23FFFFFF&style=for-the-badge)](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 camera 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
+ ### protectApi.lights[]
68
+ The `lights` property maintains the list of all known Protect light devices. It is an array of `ProtectLightConfig` 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 `ProtectLightConfig` object.
69
+
70
+ This property is refreshed each time `refreshDevices()` is called.
71
+
72
+ ### protectApi.sensors[]
73
+ The `sensors` property maintains the list of all known Protect sensor devices. It is an array of `ProtectSensorConfig` 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 `ProtectSensorConfig` object.
74
+
75
+ This property is refreshed each time `refreshDevices()` is called.
76
+
77
+ ### protectApi.viewers[]
78
+ The `viewers` property maintains the list of all known Protect viewer devices. It is an array of `ProtectViewerConfig` 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 `ProtectViewerConfig` object.
79
+
80
+ This property is refreshed each time `refreshDevices()` is called.
81
+
82
+ ### More to come...
83
+
84
+
85
+ ## UniFi Protect Realtime Updates API
86
+ 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.
87
+
88
+ 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.
89
+
90
+ 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.
91
+
92
+ 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.
93
+
94
+ 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.
95
+
96
+ #### Non-Ubiquiti Apps Using the Protect API
97
+ 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.
98
+
99
+ * [homebridge-unifi-protect](https://github.com/hjdhjd/homebridge-unifi-protect): Seamless integration of UniFi Protect into HomeKit with support for cameras, doorbells, and more.
100
+
101
+ #### Connecting
102
+ * 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.
103
+ * 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).
104
+ * 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).
105
+
106
+ Those are the basics and gets us up and running. Now, to explain how the updates API works...
107
+
108
+ #### Updates Websocket Binary Format
109
+ 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.
110
+
111
+ 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.
112
+
113
+ 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:
114
+
115
+ ```sh
116
+ Header Frame (8 bytes)
117
+ ----------------------
118
+ Action Frame
119
+ ----------------------
120
+ Header Frame (8 bytes)
121
+ ----------------------
122
+ Data Frame
123
+ ```
124
+
125
+ Let's look at each of these.
126
+
127
+ ##### Header Frame
128
+ 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.
129
+
130
+ A packet header is composed of 8 bytes in this order:
131
+
132
+ | Byte Offset | Description | Bits | Values
133
+ |----------------|-----------------|---------|-----------------------------------------
134
+ | 0 | Packet Type | 8 | 1 - action frame, 2 - payload frame.
135
+ | 1 | Payload Format | 8 | 1 - JSON object, 2 - UTF8-encoded string, 3 - Node Buffer.
136
+ | 2 | Deflated | 8 | 0 - uncompressed, 1 - deflated / compressed ([zlib](https://nodejs.org/api/zlib.html)-based).
137
+ | 3 | Unknown | 8 | Always 0. Possibly reserved for future use by Ubiquiti?
138
+ | 4-7 | Payload Size | 32 | Size of payload in network-byte order (big endian).
139
+
140
+ If the header has marked the payload as deflated (compressed), you'll need to inflate (uncompress) the payload before you can use it.
141
+
142
+ ##### Action Frame
143
+ The action frame identifies what the action and category that the update contains:
144
+
145
+ | Property | Description
146
+ |-------------|------------------------------------------------------------------------------------
147
+ | action | What action is being taken. Known actions are `add` and `update`.
148
+ | id | The identifier for the device we're updating.
149
+ | modelKey | The device model category that we're updating.
150
+ | newUpdateId | A new UUID generated on a per-update basis. This can be safely ignored it seems.
151
+
152
+ ##### Data Frame
153
+ 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:
154
+
155
+ | Payload Type | Description
156
+ |--------------|------------------------------------------------------------------------------------
157
+ | 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).
158
+ | 2 | A UTF8-encoded string.
159
+ | 3 | Node Buffer.
160
+
161
+ #### Tips
162
+ * `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`.
163
+ * `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.
164
+ * 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.
165
+ * JSONs are only payload type that seems to be sent, although the protocol is designed to accept all three.
166
+ * 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)).
167
+
168
+ ## Library Development Dashboard
169
+ This is mostly of interest to the true developer nerds amongst us.
170
+
171
+ [![License](https://img.shields.io/npm/l/unifi-protect?color=%230559C9&logo=open%20source%20initiative&logoColor=%23FFFFFF&style=for-the-badge)](https://github.com/hjdhjd/unifi-protect/blob/main/LICENSE.md)
172
+ [![Build Status](https://img.shields.io/github/workflow/status/hjdhjd/unifi-protect/Continuous%20Integration?color=%230559C9&logo=github-actions&logoColor=%23FFFFFF&style=for-the-badge)](https://github.com/hjdhjd/unifi-protect/actions?query=workflow%3A%22Continuous+Integration%22)
173
+ [![Dependencies](https://img.shields.io/librariesio/release/npm/unifi-protect?color=%230559C9&logo=dependabot&style=for-the-badge)](https://libraries.io/npm/uniti-protect)
174
+ [![GitHub commits since latest release (by SemVer)](https://img.shields.io/github/commits-since/hjdhjd/unifi-protect/latest?color=%230559C9&logo=github&sort=semver&style=for-the-badge)](https://github.com/hjdhjd/unifi-protect/commits/main)
package/dist/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  export * from "./protect-api";
2
- export * from "./protect-types";
2
+ export * from "./protect-api-livestream";
3
3
  export * from "./protect-api-updates";
4
+ export * from "./protect-logging";
5
+ export * from "./protect-types";
6
+ export { FetchError } from "node-fetch-cjs";
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,12 @@ 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);
19
+ __exportStar(require("./protect-api-livestream"), exports);
15
20
  __exportStar(require("./protect-api-updates"), exports);
21
+ __exportStar(require("./protect-logging"), exports);
22
+ __exportStar(require("./protect-types"), exports);
23
+ var node_fetch_cjs_1 = require("node-fetch-cjs");
24
+ Object.defineProperty(exports, "FetchError", { enumerable: true, get: function () { return node_fetch_cjs_1.FetchError; } });
16
25
  //# 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":";;;;;;;;;;;;AAAA,gDAA8B;AAC9B,kDAAgC;AAChC,wDAAsC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;;;;;;;;AAEH,gDAA8B;AAC9B,2DAAyC;AACzC,wDAAsC;AACtC,oDAAkC;AAClC,kDAAgC;AAChC,iDAA4C;AAAnC,4GAAA,UAAU,OAAA"}
@@ -0,0 +1,21 @@
1
+ /// <reference types="node" />
2
+ import { EventEmitter } from "events";
3
+ import { ProtectApi } from "./protect-api";
4
+ import { ProtectLogging } from "./protect-logging";
5
+ export declare class ProtectLivestream extends EventEmitter {
6
+ private _ftyp;
7
+ private _moov;
8
+ private api;
9
+ private errorHandler;
10
+ private log;
11
+ private name;
12
+ private segmentHandler;
13
+ private ws;
14
+ constructor(api: ProtectApi, log?: ProtectLogging);
15
+ start(cameraId: string, channel: number, segmentLength?: number, requestId?: string): Promise<boolean>;
16
+ stop(): void;
17
+ private launchLivestream;
18
+ private processLivestream;
19
+ get ftyp(): Buffer | null;
20
+ get moov(): Buffer | null;
21
+ }
@@ -0,0 +1,294 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ProtectLivestream = void 0;
7
+ /* Copyright(C) 2022, HJD (https://github.com/hjdhjd). All rights reserved.
8
+ *
9
+ * protect-api-livestream.ts: Our UniFi Protect livestream API implementation.
10
+ */
11
+ const events_1 = require("events");
12
+ const ws_1 = __importDefault(require("ws"));
13
+ /*
14
+ * The UniFi Protect livestream API is largely undocumented and has been reverse engineered mostly through
15
+ * trial and error, as well as observing the Protect controller in action. It builds on the works of others in the
16
+ * community - particularly Xcid - who have experimented and successfully gotten parts of this API decoded. As always,
17
+ * this work stands on the contributions of others and the work that's come before it, and I want to acknowledge those
18
+ * that paved the way.
19
+ *
20
+ * Let's start by defining some terms. In the MP4 world, an MP4 file (or stream) is composed of multiple atoms or segments.
21
+ * Think of these as packet types that contain specific pieces of information that are needed to put together a valid MP4 file.
22
+ * For our purposes, we're primarily interested in four types of MP4 boxes:
23
+ *
24
+ * FTYP - File type box. This contains codec and file information for the stream that follows it.
25
+ * It must be at the beginning of any stream, and preceded by the FTYP box.
26
+ * MDAT - Media data box. This contains a segment of the actual audio and video data in the MP4 stream.
27
+ * It is always paired with an MOOF box, which contains the metadata describing this payload in an MDAT box.
28
+ * MOOF - Movie fragment box. This defines the metadata for a specific segment of audio and video.
29
+ * It is always paired with an MDAT box, which contains the actual data.
30
+ * MOOV - Movie metadata box. This contains all the metadata information about the stream that follows.
31
+ * It must be at the beginning of any stream, and preceded by the FTYP box.
32
+ *
33
+ * Every fMP4 stream begins with the FTYP and MOOV boxes for the entire stream. It defines the file type,
34
+ * what the movie metadata is, and other characteristics. Think of it as the header for the entire stream.
35
+ *
36
+ * After the header, every fMP4 stream has a series of segments (sometimes called fragments, hence the term fMP4),
37
+ * that consist of a pair of moof / mdat boxes that includes all the audio and video for that segment. You end up with something
38
+ * that looks like:
39
+ *
40
+ * |ftyp|moov|moof|mdat|moof|mdat...
41
+ *
42
+ * The UniFi Protect livestream API provides a straightforward interface to generate bespoke fMP4 streams that
43
+ * can be tailored depending on your needs. This API allows you to create those streams, and retrieve all the relevant boxes/atoms
44
+ * you need to manipulate them for your application.
45
+ */
46
+ // A complete description of the UniFi Protect livestream API websocket API.
47
+ var ProtectLiveFrame;
48
+ (function (ProtectLiveFrame) {
49
+ ProtectLiveFrame[ProtectLiveFrame["KEYFRAME"] = 247] = "KEYFRAME";
50
+ ProtectLiveFrame[ProtectLiveFrame["FTYP"] = 248] = "FTYP";
51
+ ProtectLiveFrame[ProtectLiveFrame["BEGINSEGMENT"] = 249] = "BEGINSEGMENT";
52
+ ProtectLiveFrame[ProtectLiveFrame["MOOV"] = 250] = "MOOV";
53
+ ProtectLiveFrame[ProtectLiveFrame["MOOF"] = 251] = "MOOF";
54
+ ProtectLiveFrame[ProtectLiveFrame["VIDEO"] = 252] = "VIDEO";
55
+ ProtectLiveFrame[ProtectLiveFrame["AUDIO"] = 253] = "AUDIO";
56
+ ProtectLiveFrame[ProtectLiveFrame["MDAT"] = 254] = "MDAT";
57
+ ProtectLiveFrame[ProtectLiveFrame["ENDSEGMENT"] = 255] = "ENDSEGMENT";
58
+ })(ProtectLiveFrame || (ProtectLiveFrame = {}));
59
+ // UniFi Protect livestream API implementation.
60
+ class ProtectLivestream extends events_1.EventEmitter {
61
+ // Create a new instance.
62
+ constructor(api, log = api.log) {
63
+ // Initialize the event emitter.
64
+ super();
65
+ this._ftyp = null;
66
+ this._moov = null;
67
+ this.api = api;
68
+ this.errorHandler = null;
69
+ this.log = log;
70
+ this.name = api.getNvrName.bind(api);
71
+ this.segmentHandler = null;
72
+ this.ws = null;
73
+ }
74
+ // Start the UniFi Protect livestream.
75
+ async start(cameraId, channel, segmentLength = 100, requestId = cameraId + "-" + channel.toString()) {
76
+ // Stop any existing stream.
77
+ this.stop();
78
+ // Clear out the movie metadata atom.
79
+ this._ftyp = null;
80
+ this._moov = null;
81
+ // Launch the livestream.
82
+ return await this.launchLivestream(cameraId, channel, segmentLength, requestId);
83
+ }
84
+ // Stop the UniFi Protect livestream.
85
+ stop() {
86
+ var _a, _b, _c, _d, _e;
87
+ // Close the websocket.
88
+ if ((((_a = this.ws) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.CLOSING) || (((_b = this.ws) === null || _b === void 0 ? void 0 : _b.readyState) === ws_1.default.OPEN)) {
89
+ (_c = this.ws) === null || _c === void 0 ? void 0 : _c.terminate();
90
+ }
91
+ // Clean up our segment processing handler.
92
+ if (this.errorHandler) {
93
+ (_d = this.ws) === null || _d === void 0 ? void 0 : _d.removeListener("error", this.errorHandler);
94
+ this.errorHandler = null;
95
+ }
96
+ if (this.segmentHandler) {
97
+ (_e = this.ws) === null || _e === void 0 ? void 0 : _e.removeListener("message", this.segmentHandler);
98
+ this.segmentHandler = null;
99
+ }
100
+ // Flag that we are no longer running.
101
+ this.ws = null;
102
+ }
103
+ // Configure the websocket to populate the prebuffer.
104
+ async launchLivestream(cameraId, channel, segmentLength, requestId) {
105
+ var _a;
106
+ // To ensure there are minimal performance implications to the Protect NVR, enforce a 100ms floor for
107
+ // segment length. Protect happens to default to a 100ms segment length as well, so we do too.
108
+ if (segmentLength < 100) {
109
+ segmentLength = 100;
110
+ }
111
+ // Parameters that can be set for the livestream. We allow the modification of a useful subset of these,
112
+ // though not all of them, in order to simplify the API experience and ensure things always work.
113
+ //
114
+ // allowPartialGOP: Allow partial groups of pictures. This is necessary for a valid fMP4 stream that can be used in realtime.
115
+ // camera: The camera ID of the camera you are trying to livestream.
116
+ // channel: The camera channel to use for this livestream.
117
+ // extendedVideoMetadata: Provide extended metadata in the MOOV box when possible.
118
+ // fragmentDurationMillis: Length of each fMP4 segment or fragment, in milliseconds.
119
+ // progressive: Enable progressive livestreaming.
120
+ // rebaseTimestampsToZero: Rebase the timestamps of each segment to zero. Otherwise, timestamps will reflect the controller's default.
121
+ // requestId: Name for this particular request. It's optional in practice, and can be any string.
122
+ // type: Container format type. The valid values are fmp4 and UBV (UniFi Video proprietary format).
123
+ const params = new URLSearchParams({
124
+ allowPartialGOP: "",
125
+ camera: cameraId,
126
+ channel: channel.toString(),
127
+ extendedVideoMetadata: "",
128
+ fragmentDurationMillis: segmentLength.toString(),
129
+ progressive: "",
130
+ rebaseTimestampsToZero: "false",
131
+ requestId: requestId,
132
+ type: "fmp4"
133
+ });
134
+ // Generate our websocket endpoint URL.
135
+ const url = this.api.wsUrl() + "/livestream?" + params.toString();
136
+ this.log.debug("%s: Opening livestream websocket URL: %s", this.name(), url);
137
+ // Get the websocket.
138
+ const wsUrl = await this.api.getWsEndpoint(url);
139
+ // We ran into a problem getting the websocket URL. We're done.
140
+ if (!wsUrl) {
141
+ this.log.error("%s: Unable to retrieve the livestream websocket API endpoint from the UniFi Protect controller.", this.name());
142
+ return false;
143
+ }
144
+ try {
145
+ // Open the livestream websocket.
146
+ this.ws = new ws_1.default(wsUrl, { rejectUnauthorized: false });
147
+ if (!this.ws) {
148
+ this.ws = null;
149
+ this.log.error("%s: Unable to connect to the livestream websocket API endpoint.", this.name());
150
+ return false;
151
+ }
152
+ // Catch any errors and inform the user, if needed.
153
+ (_a = this.ws) === null || _a === void 0 ? void 0 : _a.once("error", this.errorHandler = (error) => {
154
+ // Ignore timeout errors, but notify the user about anything else.
155
+ if (error.code !== "ETIMEDOUT") {
156
+ this.log.error("%s: Error while communicating with the livestream websocket API: %s", this.name(), error);
157
+ }
158
+ this.stop();
159
+ });
160
+ // Process packets coming to our websocket.
161
+ this.processLivestream();
162
+ }
163
+ catch (error) {
164
+ this.log.error("%s: Error while connecting to the livestream websocket API: %s", this.name(), error);
165
+ this.stop();
166
+ }
167
+ return true;
168
+ }
169
+ // Process fMP4 packets as they arrive over the websocket.
170
+ processLivestream() {
171
+ // Check to ensure our websocket is live.
172
+ if (!this.ws) {
173
+ return;
174
+ }
175
+ let currentSegment = {
176
+ audio: Buffer.alloc(0),
177
+ keyframe: Buffer.alloc(0),
178
+ mdat: Buffer.alloc(0),
179
+ moof: Buffer.alloc(0),
180
+ video: Buffer.alloc(0)
181
+ };
182
+ let packetRemaining = Buffer.alloc(0);
183
+ // Process data coming in from the websocket.
184
+ this.ws.on("message", this.segmentHandler = (packet) => {
185
+ // If we have anything left from the last packet we processed, prepend it to this packet.
186
+ if (packetRemaining.length > 0) {
187
+ packet = Buffer.concat([packetRemaining, packet]);
188
+ packetRemaining = Buffer.alloc(0);
189
+ }
190
+ let offset = 0;
191
+ for (;;) {
192
+ // If we have less than 4 bytes remaining, it's an incomplete packet and we don't have enough
193
+ // information to decode it since we need the packet header to decode. We save it to prepend
194
+ // to the next packet that comes across.
195
+ if ((packet.length - offset) < 4) {
196
+ packetRemaining = packet.slice(offset);
197
+ break;
198
+ }
199
+ // Grab the encoded packet header.
200
+ const offsetWithHeader = offset + 4;
201
+ const header = packet.slice(offset, offsetWithHeader);
202
+ // Ensure we have a valid header before we do anything.
203
+ if (!(header[0] in ProtectLiveFrame)) {
204
+ this.log.error("%s: Invalid header found while decoding the livestream: %s", this.name(), header[0]);
205
+ break;
206
+ }
207
+ // Get the length of the actual fMP4 segment we are decoding. Since all this is done over a websocket,
208
+ // portions of an fMP4 segment can span packets and need to be encoded. Protect encodes the length
209
+ // of the entire fMP4 segment in the first three bytes of the header like so...
210
+ const segmentLength = (((header[1] << 8) | header[2]) << 8) | header[3];
211
+ // Once we know our length, if we don't have the complete packet, we save it and punt until we see
212
+ // more data come across.
213
+ if (packet.length < (offset + segmentLength + 4)) {
214
+ packetRemaining = packet.slice(offset);
215
+ break;
216
+ }
217
+ // Grab the data portion of the packet.
218
+ const data = packet.slice(offsetWithHeader, offsetWithHeader + segmentLength);
219
+ let completeSegment = null;
220
+ // Figure out which data type we've got based on our header, and process it.
221
+ switch (header[0]) {
222
+ // We've got audio data. Add it to our current segment.
223
+ case ProtectLiveFrame.AUDIO:
224
+ currentSegment.audio = Buffer.concat([currentSegment.audio, data]);
225
+ break;
226
+ // End of segment. Build the entire segment, and emit our events.
227
+ case ProtectLiveFrame.ENDSEGMENT:
228
+ completeSegment = Buffer.concat([currentSegment.moof, currentSegment.mdat, currentSegment.video, currentSegment.audio]);
229
+ this.emit("segment", completeSegment);
230
+ this.emit("message", completeSegment);
231
+ break;
232
+ // FTYP data. Build the FTYP box and emit our events.
233
+ case ProtectLiveFrame.FTYP:
234
+ // Write the ftyp header. The first four bytes represent the length of this atom, the next four designate the atom type.
235
+ this._ftyp = Buffer.alloc(8);
236
+ this._ftyp.writeUInt32BE(data.length + 8);
237
+ this._ftyp.write("ftyp", 4);
238
+ // Create the complete atom.
239
+ this._ftyp = Buffer.concat([this._ftyp, data]);
240
+ this.emit("ftyp", this.ftyp);
241
+ this.emit("message", this.ftyp);
242
+ break;
243
+ // Beginning of segment. Create an empty segment to get started.
244
+ case ProtectLiveFrame.BEGINSEGMENT:
245
+ currentSegment = {
246
+ audio: Buffer.alloc(0),
247
+ keyframe: Buffer.alloc(0),
248
+ mdat: Buffer.alloc(0),
249
+ moof: Buffer.alloc(0),
250
+ video: Buffer.alloc(0)
251
+ };
252
+ break;
253
+ // We've got a keyframe. Add it to our current segment.
254
+ case ProtectLiveFrame.KEYFRAME:
255
+ currentSegment.keyframe = data;
256
+ break;
257
+ // MDAT box. Add it to the MDAT portion of our segment.
258
+ case ProtectLiveFrame.MDAT:
259
+ currentSegment.mdat = Buffer.concat([currentSegment.mdat, data]);
260
+ break;
261
+ // MOOF box. Add it to the MOOF portion of our segment.
262
+ case ProtectLiveFrame.MOOF:
263
+ currentSegment.moof = Buffer.concat([currentSegment.moof, data]);
264
+ break;
265
+ // MOOV box. Add it to the MOOV portion of our segment and emit our events.
266
+ case ProtectLiveFrame.MOOV:
267
+ this._moov = data;
268
+ this.emit("moov", this.moov);
269
+ this.emit("message", this.moov);
270
+ break;
271
+ // We've got video data. Add it to our current segment.
272
+ case ProtectLiveFrame.VIDEO:
273
+ currentSegment.video = Buffer.concat([currentSegment.video, data]);
274
+ break;
275
+ // We'll never get here since we check our header information above.
276
+ default:
277
+ break;
278
+ }
279
+ // Move the offset to the next segment.
280
+ offset = offsetWithHeader + segmentLength;
281
+ }
282
+ });
283
+ }
284
+ // Retrieve the FTYP box, if we've seen it.
285
+ get ftyp() {
286
+ return this._ftyp;
287
+ }
288
+ // Retrieve the MOOV box, if we've seen it.
289
+ get moov() {
290
+ return this._moov;
291
+ }
292
+ }
293
+ exports.ProtectLivestream = ProtectLivestream;
294
+ //# sourceMappingURL=protect-api-livestream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protect-api-livestream.js","sourceRoot":"","sources":["../src/protect-api-livestream.ts"],"names":[],"mappings":";;;;;;AAAA;;;GAGG;AACH,mCAAsC;AAGtC,4CAA2B;AAE3B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,4EAA4E;AAC5E,IAAK,gBAWJ;AAXD,WAAK,gBAAgB;IAEnB,iEAAc,CAAA;IACd,yDAAU,CAAA;IACV,yEAAkB,CAAA;IAClB,yDAAU,CAAA;IACV,yDAAU,CAAA;IACV,2DAAW,CAAA;IACX,2DAAW,CAAA;IACX,yDAAU,CAAA;IACV,qEAAgB,CAAA;AAClB,CAAC,EAXI,gBAAgB,KAAhB,gBAAgB,QAWpB;AAED,+CAA+C;AAC/C,MAAa,iBAAkB,SAAQ,qBAAY;IAWjD,yBAAyB;IACzB,YAAY,GAAe,EAAE,GAAG,GAAG,GAAG,CAAC,GAAG;QAExC,gCAAgC;QAChC,KAAK,EAAE,CAAC;QAER,IAAI,CA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AgB,CAAC,IAAI;wBAExB,cAAc,CAAC,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAE,cAAc,CAAC,IAAI,EAAE,IAAI,CAAE,CAAC,CAAC;wBACnE,MAAM;oBAER,uDAAuD;oBACvD,KAAK,gBAAgB,CAAC,IAAI;wBAExB,cAAc,CAAC,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAE,cAAc,CAAC,IAAI,EAAE,IAAI,CAAE,CAAC,CAAC;wBACnE,MAAM;oBAER,2EAA2E;oBAC3E,KAAK,gBAAgB,CAAC,IAAI;wBAExB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;wBAClB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;wBAC7B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;wBAChC,MAAM;oBAER,uDAAuD;oBACvD,KAAK,gBAAgB,CAAC,KAAK;wBAEzB,cAAc,CAAC,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,CAAE,cAAc,CAAC,KAAK,EAAE,IAAI,CAAE,CAAC,CAAC;wBACrE,MAAM;oBAER,oEAAoE;oBACpE;wBAEE,MAAM;iBACT;gBAED,uCAAuC;gBACvC,MAAM,GAAG,gBAAgB,GAAG,aAAa,CAAC;aAC3C;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IAED,2CAA2C;IAC3C,IAAW,IAAI;QAEb,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,2CAA2C;IAC3C,IAAW,IAAI;QAEb,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;CACF;AAnUD,8CAmUC"}
@@ -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: Logging, packet: Buffer): ProtectNvrUpdatePacket | null;
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,GAAG,CAAC,CAAC;AAEpC,oCAAoC;AACpC,IAAK,gBAGJ;AAHD,WAAK,gBAAgB;IACnB,2DAAU,CAAA;IACV,6DAAW,CAAA;AACb,CAAC,EAHI,gBAAgB,KAAhB,gBAAgB,QAGpB;AAED,qCAAqC;AACrC,IAAK,iBAIJ;AAJD,WAAK,iBAAiB;IACpB,yDAAQ,CAAA;IACR,6DAAU,CAAA;IACV,6DAAU,CAAA;AACZ,CAAC,EAJI,iBAAiB,KAAjB,iBAAiB,QAIrB;AAED;;;;;;;;GAQG;AACH,IAAK,kBAMJ;AAND,WAAK,kBAAkB;IACrB,2DAAQ,CAAA;IACR,+EAAkB,CAAA;IAClB,mEAAY,CAAA;IACZ,iEAAW,CAAA;IACX,2EAAgB,CAAA;AAClB,CAAC,EANI,kBAAkB,KAAlB,kBAAkB,QAMtB;AAuCD,MAAa,iBAAiB;IAE5B,mEAAmE;IAC5D,MAAM,CAAC,kBAAkB,CAAC,GAAY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