-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
executable file
·448 lines (340 loc) · 11.7 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
var XbmcApi = require('xbmc'),
util = require('util'),
stream = require('stream'),
http = require('http'),
https = require('https');
// ES: This code is horrid. Please fix it.
util.inherits(driver,stream);
util.inherits(XBMCDevice,stream);
function serviceToHostIdentifier(service) {
return service.name.replace(/[^a-zA-Z0-9]/g, '') + service.port;
}
function driver(opts, app) {
this._app = app;
this._opts = opts;
this._opts.xbmc = opts.xbmc || {};
this._devices = {};
var initialised = false;
app.on('client::up',function(){
if (!initialised) {
initialised = true;
for (var ip in opts.xbmc) {
this.add(ip, opts.xbmc[ip]);
}
}
this.scan();
}.bind(this));
}
driver.prototype.config = function(rpc,cb) {
var self = this;
if (!rpc) {
return cb(null,{"contents":[
{ "type": "submit", "name": "Add manually using IP address", "rpc_method": "addModal" },
{ "type": "submit", "name": "RickRoll All The Things!", "rpc_method": "rick-roll" }
]});
}
switch (rpc.method) {
case 'addModal':
cb(null, {
"contents":[
{ "type": "paragraph", "text":"Please enter the IP address of the XBMC instance as well a nickname."},
{ "type": "input_field_text", "field_name": "ip", "value": "", "label": "IP", "placeholder": "x.x.x.x", "required": true},
{ "type": "input_field_text", "field_name": "name", "value": "XBMC", "label": "Name", "placeholder": "LoungeRoom", "required": true},
{ "type": "paragraph", "text":"Note: You must enable the JSON-RPC interface with the xbmc setting 'Allow programs on other systems to control XBMC'"},
{ "type": "submit", "name": "Add", "rpc_method": "add" }
]
});
break;
case 'add':
self._opts.xbmc[rpc.params.ip] = rpc.params.name;
self.save();
self.add(rpc.params.ip, rpc.params.name);
cb(null, {
"contents": [
{ "type":"paragraph", "text":"XBMC at http://" + rpc.params.ip + ":9090 (name : " + rpc.params.name + ") added."},
{ "type":"close", "text":"Close"}
]
});
break;
case 'rick-roll':
self.rickRoll();
cb(null, {
"contents": [
{ "type":"paragraph", "text":"<img src='http://www.schwimmerlegal.com/rickroll.jpg'/>"},
{ "type":"close", "text":"Close"}
]
});
break;
default:
self.log.warn('Unknown rpc method', rpc.method, rpc);
}
};
driver.prototype.rickRoll = function() {
for (ip in this._devices) {
var device = this._devices[ip];
this.log.info('rickrolling', device.G);
device._xbmc.player.openYoutube('dQw4w9WgXcQ');
}
};
driver.prototype.add = function(ip, name, service) {
if (this._devices[ip]) {
return;
}
this.log.info('Xbmc: Adding:' + name + ' (' + ip + ')');
var self = this;
var parentDevice = new XBMCDevice(ip, (service != null && service.port) ? service.port : 9090, name, self._app, self);
self._devices[ip] = parentDevice;
if ( service ) {
parentDevice.addAddresses( service.addresses );
}
Object.keys(parentDevice.devices).forEach(function(id) {
self.log.debug('Adding sub-device', id, parentDevice.devices[id].G);
self.emit('register', parentDevice.devices[id]);
});
};
driver.prototype.scan = function () {
var mdns;
try {
mdns = require('mdns');
} catch(e) {
this.log.warn('MDNS not available. Automatically discovery of XBMC using ZeroConf is not possible.');
return;
}
this.log.debug('MDNS: Scanning');
var self = this;
var browser = new mdns.Browser(mdns.tcp('xbmc-jsonrpc'));
browser.on('serviceUp', function(service) {
self.log.info("MDNS: service up: ", service);
var hostId = serviceToHostIdentifier(service);
if (!self._devices[hostId]) {
self.add(hostId, service.name, service);
} else {
self._devices[hostId].addAddresses( service.addresses );
self.log.debug("Skipping already seen XBMC instance (instead, adding as alternative host):", hostId);
}
});
browser.on('serviceDown', function(service) {
this.log.info("MDNS: service down: ", service);
}.bind(this));
browser.start();
};
module.exports = driver;
function XBMCDevice(host, port, name, app, driver) {
this.host = host;
this.port = port;
this.name = name && name.length > 0? name : host;
this.app = app;
this.log = driver.log.extend? driver.log.extend(name) : driver.log;
this._connections = [];
this.addAddresses([host]);
this._xbmc = new XbmcApi.XbmcApi({silent:true});
this._nextConnection = 0;
this.bindNextConnection( );
var self = this;
this._xbmc.on('connection:open', function() {
self.devices.hid.emit('data', 'connected');
//self.devices.camera.emit('data', 1);
//self.devices.displayText.emit('data', 1);
//self.devices.temperature.emit('data', 'xxx');
//self._xbmc.message('Online.', 'NinjaBlocks', 1000);// 'http://www.sydneyangels.net.au/wp-content/uploads/2012/09/ninjablocks_logo.png');
});
this._xbmc.on('connection:close', function() {
//log('Xbmc connection closed. Reconnecting in 10 seconds');
var timeout = 2000; // take 500ms between address attempts
if ( this._nextConnection == 0 ) {
timeout = 10000; // take 10s between retries after disconnect
} else {
self.log.info('Could not connect to', self._xbmc.connection.options.host, ', retrying with next address...' );
}
setTimeout(self.bindNextConnection.bind(self), timeout);
});
'play,pause,stop,add,update,clear,scanstarted,scanfinished,screensaveractivated,screensaverdeactivated,wake,sleep,seek'
.split(',').forEach( function listenToNotification(name) {
self._xbmc.on('notification:'+name, function(e) {
self.log.debug( 'Notification', name );
self.devices.hid.emit('data', name);
});
});
self._xbmc.on('connection:data', function(e) {
self.log.debug('onData', e);
});
function hid() {
this.readable = true;
this.writeable = true;
this.V = 0;
this.D = 14;
this.G = serviceToHostIdentifier(self);
}
util.inherits(hid, stream);
hid.prototype.write = function(data) {
self._xbmc.input.ExecuteAction(data);
};
function displayText() {
this.readable = true;
this.writeable = true;
this.V = 0;
this.D = 240;
this.G = serviceToHostIdentifier(self);
}
util.inherits(displayText, stream);
displayText.prototype.write = function(data) {
self.log.info('Received text to display', data);
if (typeof data == 'string') {
try {
data = JSON.parse(data);
} catch(e) {
data = {message:data};
}
}
self._xbmc.message(
data.message,
data.title || 'NinjaBlocks',
data.time || 5000,
data.image || 'https://s3.amazonaws.com/ksr/avatars/1816468/Ninja-Blocks-Vimeo-Logo.medium.jpg?1345467110'
);
return true;
};
function temperature() {
this.readable = true;
this.writeable = false;
this.V = 0;
this.D = 202;
this.G = serviceToHostIdentifier(self);
var device = this;
setInterval(function() {
self.getInfoLabels(['System.CPUTemperature'], function(data) {
var celsius = (parseFloat(data['System.CPUTemperature'].match(/[0-9\.]*/))- 32) * 5 / 9;
device.emit('data', celsius.toFixed(1));
});
}, 10000);
}
util.inherits(temperature, stream);
function camera() {
this.writeable = true;
this.readable = true;
this.V = 0;
this.D = 1004;
this.G = serviceToHostIdentifier(self);
this._guid = [self.app.id,this.G,this.V,this.D].join('_');
self.log.debug("Camera guid", this._guid);
}
util.inherits(camera, stream);
camera.prototype.write = function(data) {
var postOptions = {
host:self.app.opts.streamHost,
port:self.app.opts.streamPort,
path:'/rest/v0/camera/'+this._guid+'/snapshot',
method:'POST'
};
var proto = (self.app.opts.streamPort==443) ? https:http;
self.log.debug('Requesting current playing');
self._xbmc.media.api.send('Player.GetActivePlayers').then(function(data) {
if (data.result && data.result.length) {
self._xbmc.media.api.send('Player.GetItem', {
playerid: data.result[0].playerid,
properties: ['thumbnail']
}).then(function(data) {
if (!data.result.item.thumbnail) {
console.warn("No thumbnail available!");
return;
}
var thumbnail = "http://" + self.host + ':8080/image/' + encodeURIComponent(data.result.item.thumbnail);
self.log.debug('Sending thumbnail : ' + thumbnail);
var getReq = http.get(thumbnail,function(getRes) {
postOptions.headers = getRes.headers;
postOptions.headers['X-Ninja-Token'] = self.app.token;
self.log.debug('token', self.app.token);
var postReq = proto.request(postOptions,function(postRes) {
postRes.on('end',function() {
self.log.debug('Stream Server ended');
});
postRes.resume();
});
postReq.on('error',function(err) {
self.log.error('Error sending picture: ');
self.log.error(err);
});
var lenWrote=0;
getRes.on('data',function(data) {
postReq.write(data,'binary');
lenWrote+=data.length;
});
getRes.on('end',function() {
postReq.end();
self.log.debug("Image sent %s",lenWrote);
});
getRes.resume();
});
getReq.on('error',function(error) {
self.log.debug(error);
});
getReq.end();
});
} else {
self.log.debug("Nothing is currently playing");
}
});
return true;
};
this.devices = {
hid: new hid(),
camera: new camera(),
displayText: new displayText(),
temperature: new temperature()
};
}
XBMCDevice.prototype.addAddresses = function(addresses) {
var self = this;
addresses.forEach(function(address){
self._connections.push( new XbmcApi.TCPConnection({
host: address,
port: self.port,
verbose: false,
connectNow: false
}) );
});
};
XBMCDevice.prototype.bindNextConnection = function () {
var conn = this._nextConnection;
this._nextConnection = (this._nextConnection+1) % this._connections.length;
this._connections[conn].create();
this._xbmc.setConnection(this._connections[conn]);
};
XBMCDevice.prototype.getInfoLabels = function(labels, cb) {
this._xbmc.player.api.send('XBMC.GetInfoLabels', {
labels: labels
}).then(function(data) {
//log('xxx', data);
cb(data.result);
});
};
XBMCDevice.prototype.end = function() {};
XBMCDevice.prototype.close = function() {};
/*
var dumpEvent = function(event) {
if (event && event.method)
log(event.method, event);
};
xbmcApi.on('connection:data', function(e) {
log('onData', e);
});
xbmcApi.on('notification', function() {
log(111);
});
xbmcApi.on('connection:open', dumpEvent);
xbmcApi.on('connection:close', dumpEvent);
xbmcApi.on('connection:error', dumpEvent);
xbmcApi.on('api:movie', dumpEvent);
xbmcApi.on('api:episode', dumpEvent);
xbmcApi.on('api:playerStopped', dumpEvent);
xbmcApi.on('api:video', dumpEvent);
xbmcApi.on('notification:play', dumpEvent);
xbmcApi.on('notification:pause', dumpEvent);
xbmcApi.on('notification:add', dumpEvent);
xbmcApi.on('notification:update', dumpEvent);
xbmcApi.on('notification:clear', dumpEvent);
xbmcApi.on('notification:scanstarted', dumpEvent);
xbmcApi.on('notification:scanfinished', dumpEvent);
xbmcApi.on('notification:screensaveractivated', dumpEvent);
xbmcApi.on('notification:screensaverdeactivated', dumpEvent);
log('done');*/