forked from hjdhjd/homebridge-unifi-protect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·269 lines (218 loc) · 8.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
var Accessory, hap, UUIDGen;
var FFMPEG = require('./ffmpeg').FFMPEG;
var requestPromise = require('request-promise').defaults({jar: true});
module.exports = function(homebridge) {
Accessory = homebridge.platformAccessory;
hap = homebridge.hap;
UUIDGen = homebridge.hap.uuid;
homebridge.registerPlatform("homebridge-unifi-protect2", "Camera-UniFi-Protect", unifiPlatform, true);
}
function unifiPlatform(log, config, api) {
var self = this;
self.log = log;
self.config = config || {};
if (api) {
self.api = api;
if (api.version < 2.1) {
throw new Error("Unexpected API version.");
}
self.api.on('didFinishLaunching', self.didFinishLaunching.bind(this));
}
}
function getUnifiAuthConfig(controllerConfig, log, debugProtect) {
// Cleanup some common URL issues - eliminate multiple slashes and trailing slashes.
controllerConfig.url = 'https://' + controllerConfig.url
.replace(/^https\:\/\//, '') // Remove the leading "https://" for now.
.replace(/\/+/g, '/') // Replace consecutive slashes with a single slash.
.replace(/\/+$/, ''); // Remove trailing slashes.
if(debugProtect) {
log("Configuration URL: " + controllerConfig.url);
}
// Check to see if we're running on a CloudKey equivalent or a UnifiOS device.
return requestPromise.get(controllerConfig.url, {
rejectUnauthorized: false,
resolveWithFullResponse: true
}).then(response => {
if (response.headers['x-csrf-token']) {
if(debugProtect) {
log("UniFi Protect endpoint type identified: UnifiOS.");
}
return {
authURL: controllerConfig.url + '/api/auth/login',
bootstrapURL: controllerConfig.url + '/proxy/protect/api/bootstrap',
isUnifiOS: true,
csrfToken: response.headers['x-csrf-token']
}
} else {
if(debugProtect) {
log("UniFi Protect endpoint type identified: CloudKey Gen2+ or similar.");
}
return {
authURL: controllerConfig.url + '/api/auth',
bootstrapURL: controllerConfig.url + '/api/bootstrap',
isUnifiOS: false
}
}
}).catch(e => {
log.error("Error detecting endpoint type: " + e)
});
}
unifiPlatform.prototype.configureAccessory = function(accessory) {
// Shouldn't be invoked.
}
unifiPlatform.prototype.didFinishLaunching = function() {
var self = this;
var debugProtect = self.config.debugProtect === true;
var videoProcessor = self.config.videoProcessor;
var videoConfig = self.config.videoConfig;
// Set some sane defaults...
// Tell ffmpeg that this is an RTSP over a TCP stream.
var sourcePrefix = '-re -rtsp_transport tcp';
// Magic incantation to stream effectively to iOS at the best quality possible.
var additionalCommandline = '-preset slow -profile:v high -level 4.2 -x264-params intra-refresh=1:bframes=0';
// Map audio and video to deal with UniFi quirks.
var mapaudio = '0:0';
var mapvideo = '0:1';
// Set a reasonable max FPS value. If your Protect setup is slower, this won't matter.
var maxFPS = 20;
// Set a reasonable packet size. This must be increments of 188.
var packetSize = 376;
// Set a reasonable stream maximum.
var maxStreams = 4;
// Default to 1080p.
var maxWidth = 1920;
var maxHeight = 1080;
// Default to no audio. Most default ffmpeg installations do not include support for
// fdk-aac, which is a prerequisite to enabling this.
var audio = false;
if(videoConfig) {
if(videoConfig.sourcePrefix) {
sourcePrefix = videoConfig.sourcePrefix;
}
if(videoConfig.additionalCommandline) {
additionalCommandline = videoConfig.additionalCommandline;
}
if(videoConfig.mapaudio) {
mapaudio = videoConfig.mapaudio;
}
if(videoConfig.mapvideo) {
mapvideo = videoConfig.mapvideo;
}
if(videoConfig.maxFPS) {
maxFPS = videoConfig.maxFPS;
}
if(videoConfig.maxStreams) {
maxStreams = videoConfig.maxStreams;
}
if(videoConfig.maxWidth) {
maxWidth = videoConfig.maxWidth;
}
if(videoConfig.maxHeight) {
maxHeight = videoConfig.maxHeight;
}
if(videoConfig.packetSize) {
packetSize = videoConfig.packetSize;
}
if(videoConfig.audio) {
audio = videoConfig.audio === true;
}
}
if (self.config.controllers) {
var controllers = self.config.controllers;
var promises = controllers.map(controllerConfig => {
return getUnifiAuthConfig(controllerConfig, self.log, debugProtect).then(unifiAuthConfig => {
var options = {
json: {
username: controllerConfig.username,
password: controllerConfig.password
},
resolveWithFullResponse: true,
rejectUnauthorized: false
}
if(unifiAuthConfig.isUnifiOS) {
options.headers = {
'X-CSRF-Token': unifiAuthConfig.csrfToken,
}
}
return requestPromise.post(
unifiAuthConfig.authURL, options)
.then(response => {
var options = {
headers: {},
rejectUnauthorized: false,
resolveWithFullResponse: true
};
if(unifiAuthConfig.isUnifiOS){
options.headers['X-CSRF-Token'] = unifiAuthConfig.csrfToken;
} else {
options.headers['Authorization'] = 'Bearer ' + response.headers.authorization;
}
return requestPromise.get(
unifiAuthConfig.bootstrapURL, options
).then(response => {
let bootstrap = JSON.parse(response.body);
// Debug logging if enabled.
if(debugProtect) {
self.log(response.body);
}
return bootstrap.cameras.map(camera => {
var cameraName = camera.name;
var channel = camera.channels.find(channel => {
return channel.isRtspEnabled == true;
});
if (!channel) {
throw new Error("No cameras with enabled RTSP channels found. Only cameras with RTSP streams enabled can be used with this plugin. Please enable RTSP on at least one camera in UniFi Protect.");
}
// Other possibilities for dealing with image snapshots...the first relies on anonymous snapshots being enabled. The second is a slightly
// fancier way of using ffmpeg to get a high-quality image snapshot. In practice, the default setting of the ffmpeg plugin works great in
// my testing.
//
// stillImageSource: '-i https://' + camera.host + '/snap.jpeg',
// stillImageSource: sourcePrefix + ' -i rtsp://' + bootstrap.nvr.host + ':' + bootstrap.nvr.ports.rtsp + '/' + channel.rtspAlias + ' -q:v 0',
var cameraConfig = {
name: cameraName,
videoConfig: {
source: sourcePrefix + ' -i rtsp://' + bootstrap.nvr.host + ':' + bootstrap.nvr.ports.rtsp + '/' + channel.rtspAlias,
additionalCommandline: additionalCommandline,
mapvideo: mapvideo,
mapaudio: mapaudio,
maxStreams: maxStreams,
maxWidth: maxWidth,
maxHeight: maxHeight,
maxFPS: maxFPS,
packetSize: packetSize,
audio: audio,
debug: debugProtect
}
}
var uuid = UUIDGen.generate(cameraName);
var cameraAccessory = new Accessory(cameraName, uuid, hap.Accessory.Categories.CAMERA);
cameraAccessory.getService(hap.Service.AccessoryInformation)
.setCharacteristic(hap.Characteristic.Manufacturer, 'Ubiquiti Networks')
.setCharacteristic(hap.Characteristic.Model, camera.type)
.setCharacteristic(hap.Characteristic.HardwareRevision, camera.hardwareRevision)
.setCharacteristic(hap.Characteristic.FirmwareRevision, camera.firmwareVersion)
.setCharacteristic(hap.Characteristic.SerialNumber, camera.mac);
var cameraSource = new FFMPEG(hap, cameraConfig, self.log, videoProcessor);
cameraAccessory.configureCameraSource(cameraSource);
return cameraAccessory;
});
}).catch(e => {
self.log.error("Unable to bootstrap cameras from UniFi Protect controller: " + e);
});
}).then(result => {
return result;
}).catch(e => {
self.log.error("Error connecting to UniFi Protect controller - verify the URL setting you configured: " + e);
})
});
});
Promise.all(promises).then(controllerAccessories => {
controllerAccessories.forEach(accessories => {
self.api.publishCameraAccessories("homebridge-unifi-protect2", accessories);
});
}).catch(e => {
self.log.error("Unable to register cameras with HomeKit: " + e);
});
}
}