forked from jishi/node-sonos-http-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
115 lines (94 loc) · 2.33 KB
/
server.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
var http = require('http');
var SonosDiscovery = require('sonos-discovery');
var fs = require('fs');
var discovery = new SonosDiscovery();
var port = 5005;
var presets = {};
fs.exists('./presets.json', function (exists) {
if (exists) {
presets = require('./presets.json');
console.log('loaded presets', presets);
} else {
console.log('no preset file, ignoring...');
}
});
var server = http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain',
'Cache-Control': 'no-cache'
});
var params = req.url.substring(1).split('/');
if (params.length < 2 && params[0] !== "zones") {
res.end();
return;
} else if (params.length == 2 && params[0] == "preset") {
// Handle presets
var opt = {
action: params[0],
value: params[1]
};
} else if (params.length > 1) {
var opt = {
room: params[0],
action: params[1],
value: params[2]
};
} else {
// guessing zones
var opt = {
action: params[0]
}
}
var response = handleAction(opt);
if (response) {
var jsonResponse = JSON.stringify(response);
res.write(new Buffer(jsonResponse));
}
res.end();
});
function handleAction(options) {
if (options.action === "zones") {
return discovery.getZones();
}
if (options.action == "preset") {
// Apply preset
var value = decodeURIComponent(options.value);
if (value.startsWith('{'))
var preset = JSON.parse(value);
else
var preset = presets[value];
if (preset)
discovery.applyPreset(preset);
}
var roomName = decodeURIComponent(options.room);
var player = discovery.getPlayer(roomName);
if (!player) return;
console.log(options);
switch (options.action.toLowerCase()) {
case "play":
player.coordinator.play();
break;
case "pause":
player.coordinator.pause();
break;
case "volume":
player.setVolume(options.value);
break;
case "state":
return player.coordinator.state;
break;
case "seek":
player.coordinator.seek(options.value);
break;
case "next":
player.coordinator.nextTrack();
break;
case "previous":
player.coordinator.previousTrack();
break;
case "setavtransport":
player.setAVTransportURI(options.value);
}
}
server.listen(port);
console.log("http server listening on port", port);