forked from velocityzen/node-upnp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
312 lines (253 loc) · 8.33 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
const http = require('http');
const os = require('os');
const { URL } = require('url');
const EventEmitter = require('events');
const got = require('got');
const concat = require('concat-stream');
const address = require('network-address');
const version = require('./package.json');
const DEFAULT_USER_AGENT = `${os.platform()}/${os.release()} UPnP/1.1 ${version.name}/${version.version}`;
const SUBSCRIPTION_TIMEOUT = 300;
const SUBSCRIPTION_TIMEOUT_MIN = 30;
const { parseDeviceDescription, parseServiceDescription, parseSOAPResponse, parseEvents, parseTimeout } = require('./response');
const { createSOAPAction } = require('./request');
const { resolveService } = require('./util');
const error = require('./error');
class UPnPClient {
constructor({ url, userAgent = DEFAULT_USER_AGENT }) {
this.url = new URL(url);
this.deviceDescription = null;
this.serviceDescriptions = {};
this.eventsServer = null;
this.subscriptions = {};
this.eventEmitter = new EventEmitter();
this.handleStateUpdate = this.handleStateUpdate.bind(this);
this.client = got.extend({
headers: {
'user-agent': userAgent
}
});
}
async getDeviceDescription() {
if (!this.deviceDescription) {
const response = await this.client(this.url);
this.deviceDescription = parseDeviceDescription(response.body, this.url);
}
return this.deviceDescription;
}
async hasService(serviceId) {
serviceId = resolveService(serviceId);
const description = await this.getDeviceDescription();
return Boolean(description.services[serviceId]);
}
async getServiceDescription(serviceId) {
if (!(await this.hasService(serviceId))) {
throw error.NoService(serviceId);
}
const service = this.deviceDescription.services[serviceId];
if (!this.serviceDescriptions[serviceId]) {
const response = await this.client(service.SCPDURL);
this.serviceDescriptions[serviceId] = parseServiceDescription(response.body);
}
return this.serviceDescriptions[serviceId];
}
async getVariableServiceId(variable, force) {
const { services } = await this.getDeviceDescription();
for (const serviceId of Object.keys(services)) {
const { stateVariables } = await this.getServiceDescription(serviceId);
if (!stateVariables) {
continue;
}
for (const v in stateVariables) {
if (v === variable && (stateVariables[v].sendEvents || force === true)) {
return serviceId;
}
}
}
}
async call(serviceId, actionName, data) {
serviceId = resolveService(serviceId);
const description = await this.getServiceDescription(serviceId);
const action = description.actions[actionName];
if (!action) {
throw error.NoAction(actionName);
}
const service = this.deviceDescription.services[serviceId];
const SOAPAction = createSOAPAction(service, actionName, data);
const res = await this.client({
throwHttpErrors: false,
url: service.controlURL,
method: 'POST',
body: SOAPAction,
headers: {
'Content-Type': 'text/xml; charset="utf-8"',
'Content-Length': SOAPAction.length,
'Connection': 'close',
'SOAPACTION': `"${service.serviceType}#${actionName}"`
}
});
if (res.statusCode !== 200) {
throw error.UPnPError(res.statusCode, res.body);
}
const result = parseSOAPResponse(res.body, actionName, action.outputs);
return result;
}
async on(variable, listener, options = {}) {
const serviceId = await this.getVariableServiceId(variable, options.force);
if (!serviceId) {
throw error.NoEvents(variable);
}
this.eventEmitter.on(variable, listener);
await this.subscribe(serviceId, this.handleStateUpdate);
}
async off(variable, listener) {
this.eventEmitter.off(variable, listener);
const serviceId = await this.getVariableServiceId(variable, true);
await this.unsubscribe(serviceId, this.handleStateUpdate);
}
emit(...args) {
this.eventEmitter.emit(...args);
}
async removeAllListeners() {
this.eventEmitter.removeAllListeners();
await this.clearSubscriptions();
}
handleStateUpdate(e) {
this.eventEmitter.emit(e.name, e.value);
}
async subscribe(serviceId, listener) {
serviceId = resolveService(serviceId);
const subs = this.subscriptions[serviceId];
if (subs) {
if (!subs.listeners.includes(listener)) {
this.subscriptions[serviceId].listeners.push(listener);
}
return;
}
if (!(await this.hasService(serviceId))) {
throw error.NoService(serviceId);
}
const service = this.deviceDescription.services[serviceId];
const server = await this.getEventsServer();
const url = new URL(service.eventSubURL);
const res = await this.client({
url,
throwHttpErrors: false,
method: 'SUBSCRIBE',
headers: {
'HOST': url.host,
'CALLBACK': `<http://${server.address().address}:${server.address().port}/>`,
'NT': 'upnp:event',
'TIMEOUT': `Second-${SUBSCRIPTION_TIMEOUT}`
}
})
if (res.statusCode !== 200) {
this.stopEventsServer();
throw error.Subscribe(res.statusCode);
}
const { sid, timeout } = res.headers;
const renewTimeout = Math.max(parseTimeout(timeout) - SUBSCRIPTION_TIMEOUT_MIN, SUBSCRIPTION_TIMEOUT_MIN);
const timer = setTimeout(() => this.renewSubscription({
url, sid, serviceId
}), renewTimeout * 1000);
this.subscriptions[serviceId] = {
sid, url, timer,
listeners: [ listener ]
}
}
async unsubscribe(serviceId, listener) {
serviceId = resolveService(serviceId);
const subscription = this.subscriptions[serviceId];
if (!subscription) {
return;
}
const index = subscription.listeners.indexOf(listener);
if (index === -1) {
return;
}
subscription.listeners.splice(index, 1);
if (subscription.listeners.length !== 0) {
return;
}
clearTimeout(subscription.timer);
const res = await this.client({
url: subscription.url,
throwHttpErrors: false,
method: 'UNSUBSCRIBE',
headers: {
HOST: subscription.url.host,
SID: subscription.sid
}
});
if (res.statusCode !== 200) {
throw error.Unsubscribe(res.statusCode);
}
delete this.subscriptions[serviceId];
this.stopEventsServer();
}
async renewSubscription({ url, sid, serviceId }) {
const res = await this.client({
url,
throwHttpErrors: false,
method: 'SUBSCRIBE',
headers: {
'HOST': url.host,
'SID': sid,
'TIMEOUT': `Second-${SUBSCRIPTION_TIMEOUT}`
}
});
if (res.statusCode !== 200) {
this.stopEventsServer();
throw error.SubscriptionRenewal(res.statusCode);
}
const timeout = parseTimeout(res.headers.timeout);
const renewTimeout = Math.max(timeout - SUBSCRIPTION_TIMEOUT_MIN, SUBSCRIPTION_TIMEOUT_MIN); // renew 30 seconds before expiration
const timer = setTimeout(() => this.renewSubscription({
url, sid, serviceId
}), renewTimeout * 1000);
this.subscriptions[serviceId].timer = timer;
}
async getEventsServer() {
if (!this.eventsServer) {
this.eventsServer = await this.createEventsServer();
}
if (!this.eventsServer.listening) {
await new Promise(resolve => {
this.eventsServer.listen(0, address.ipv4(), resolve);
})
}
return this.eventsServer;
}
createEventsServer() {
return http.createServer(req =>
req.pipe(concat(buf => this.eventsServerRequestHandler(req, buf)))
);
}
eventsServerRequestHandler(req, buf) {
const { sid } = req.headers;
const events = parseEvents(buf);
const keys = Object.keys(this.subscriptions);
const serviceId = keys.find(key => this.subscriptions[key].sid === sid);
if (!serviceId) {
// silently ignore unknown SIDs
return;
}
const listeners = this.subscriptions[serviceId].listeners;
listeners.forEach(listener => events.forEach(e => listener(e)));
}
stopEventsServer() {
if (this.hasSubscriptions()) {
return;
}
this.eventsServer.close();
this.eventsServer = null;
}
hasSubscriptions() {
return Object.keys(this.subscriptions).length !== 0;
}
clearSubscriptions() {
this.subscriptions = {};
this.stopEventsServer();
}
}
module.exports = UPnPClient;