-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
263 lines (225 loc) · 7.71 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
#!/usr/bin/env node
var path = require('path');
var fs = require('fs')
var config = {
"servername": "[AirPlay Hub]",
"webuiport": 8089,
"debug": false,
"idletimout": 600,
"zones": []
};
var configPath = './config.json';
var argv = require('minimist')(process.argv.slice(2));
if (argv.h || argv.help) {
console.log('usage: node-airplayhub [options]\n options:\n -c, --config Path to config file')
process.exit();
} else {
if (argv.c) configPath = argv.c;
if (argv.config) configPath = argv.config;
if(!path.isAbsolute(configPath)) configPath = path.join(__dirname, configPath)
}
try{
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
} catch(e) {
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
}
var zones = config.zones;
var express = require('express');
var logger = require('morgan');
var app = express();
var http = require('http');
var airtunes = require('airtunes')
var airtunesserver = require('nodetunes');
var bonjour = require('bonjour')();
var connectedDevices = [];
var trackinfo = {};
var idleTimer;
var server = new airtunesserver({ serverName: config.servername, verbose: config.debug });
server.on('clientConnected', function (stream) {
clearTimeout(idleTimer);
stream.pipe(airtunes);
for (var i in zones) {
if (zones[i].enabled) {
connectedDevices[i] = airtunes.add(zones[i].host, { port: zones[i].port, volume: zones[i].volume });
}
}
});
server.on('clientDisconnected', (data) => {
clearTimeout(idleTimer);
if (config.idletimout > 0) {
idleTimer = setTimeout(() => {
airtunes.stopAll(() => {
for (var i in zones) {
zones[i].enabled = false;
}
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
});
}, config.idletimout * 1000);
}
});
server.on('metadataChange', (data) => {
trackinfo = data;
getArtwork(trackinfo.asar, trackinfo.asal, (url) => {
if (url) {
trackinfo.albumart = url;
} else {
trackinfo.albumart = '/genericart.png';
}
});
});
server.on('volumeChange', (data) => {
clearTimeout(idleTimer);
});
server.start();
if (config.debug) { app.use(logger('dev')) };
app.use('/icons', express.static(path.join(__dirname, 'root/icons'), { maxAge: '1y' }));
app.use(express.static(path.join(__dirname, 'root'), {
setHeaders: (res, path, stat) => {
res.setHeader('Cache-Control', 'public, max-age=0');
}
}));
http.createServer(app).listen(config.webuiport);
app.get('/', (req, res) => { res.redirect('/Index.html') });
app.get('/startzone/:zonename', function (req, res) {
var zonename = req.params.zonename;
var resp = { error: "zone not found" };
for (var i in zones) {
if (zones[i].name.toLowerCase() == zonename.toLowerCase()) {
connectedDevices[i] = airtunes.add(zones[i].host, { port: zones[i].port, volume: zones[i].volume });
zones[i].enabled = true;
resp = zones[i];
}
}
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
res.json(resp);
});
app.get('/stopzone/:zonename', function (req, res) {
var zonename = req.params.zonename;
var resp = { error: "zone not found" };
for (var i in zones) {
if (zones[i].name.toLowerCase() == zonename.toLowerCase()) {
zones[i].enabled = false;
if (connectedDevices[i]) {
connectedDevices[i].stop();
}
resp = zones[i];
}
}
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
res.json(resp);
});
app.get('/setvol/:zonename/:volume', function (req, res) {
var zonename = req.params.zonename;
var volume = req.params.volume;
var resp = { error: "zone not found" };
for (var i in zones) {
if (zones[i].name.toLowerCase() == zonename.toLowerCase()) {
zones[i].volume = volume;
if (connectedDevices[i]) {
connectedDevices[i].setVolume(volume);
}
resp = zones[i];
}
}
config.zones = zones;
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
res.json(resp);
});
app.get('/zones', function (req, res) {
var zonesNotHidden = zones.filter(function (z) {
return (!z.hidden);
});
res.json(zonesNotHidden);
});
app.get('/hidezone/:zonename', function (req, res) {
var zonename = req.params.zonename;
var resp = { error: "zone not found" };
for (var i in zones) {
if (zones[i].name.toLowerCase() == zonename.toLowerCase()) {
zones[i].hidden = true;
resp = zones[i];
}
}
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
res.json(resp);
});
app.get('/showzone/:zonename', function (req, res) {
var zonename = req.params.zonename;
var resp = { error: "zone not found" };
for (var i in zones) {
if (zones[i].name.toLowerCase() == zonename.toLowerCase()) {
zones[i].hidden = false;
resp = zones[i];
}
}
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
res.json(resp);
});
app.get('/trackinfo', function (req, res) {
res.json(trackinfo);
});
function getArtwork(artist, album, callback) {
var url = `http://itunes.apple.com/search?term=${artist} ${album}`;
http.get(url, function (res) {
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
var albumInfo = JSON.parse(body);
if (albumInfo.resultCount > 0) {
callback(albumInfo.results[0].artworkUrl100.replace('100x100', '600x600'));
} else {
callback('/genericart.png');
}
});
}).on('error', function (e) {
callback('/genericart.png');
});
}
function getIPAddress(service) {
addresses = service.addresses;
// Extract right IPv4 address
var rx = /^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/;
for (var a in addresses) {
// Test if we can find an ipv4 address
if (rx.test(addresses[a]) && addresses[a].lastIndexOf('169', 0) !== 0) {
return addresses[a];
break;
}
}
}
function validateDevice(service) {
// Extract IP address, hostname and port from mdns descriptor
service.ip = getIPAddress(service);
service.id = service.ip + ":" + service.port;
service.name = service.name.split('@')[1];
// Ignore self
if(service.name == config.servername) return;
// Check whether we know this zone already - if we do, do not add it again
var zoneUnknown = true;
for (var i in zones) {
if (zones[i].name.toLowerCase() == service.name.toLowerCase()) {
// Duplicate found which already existed in the config. Mind we match on the fqdn the host claims to have.
zoneUnknown = false;
}
}
// If it is a new zone, thank you very much, add it and write it to our config
// TODO: I re-used the ./config.json used elsewhere in this application. Ideally, it should take the parameter passed in --config and not just 'require' the file but properly read it and parse it and write it back here
if (zoneUnknown) {
zones.push({ "name": service.name, "host": service.ip, "port": service.port, "volume": 0, "enabled": false, "hidden": false });
config.zones = zones;
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
}
};
// browse for all raop services
var browser = bonjour.find({
type: 'raop'
});
browser.on('up', function (service) {
validateDevice(service);
});
browser.on('down', function (service) {
// TODO
});
browser.start();