iobroker.squeezeboxrpc 2.0.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,273 +0,0 @@
1
- /*
2
- The MIT License (MIT)
3
-
4
- Copyright (c) 2013-2015 Piotr Raczynski, pio[dot]raczynski[at]gmail[dot]com
5
-
6
- Permission is hereby granted, free of charge, to any person obtaining a copy
7
- of this software and associated documentation files (the "Software"), to deal
8
- in the Software without restriction, including without limitation the rights
9
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- copies of the Software, and to permit persons to whom the Software is
11
- furnished to do so, subject to the following conditions:
12
-
13
- The above copyright notice and this permission notice shall be included in all
14
- copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- SOFTWARE.
23
- */
24
-
25
- const jayson = require('jayson');
26
- // const inherits = require('super');
27
- let AWS;
28
-
29
- // address "<http|https>://|hostbame[:port]"
30
- // transport "<[0-9]*|sqs[://region]|ssh://password:username@hostname:port"
31
- // sqs password = {send: "Queue URL, recv "Queue URL" }
32
-
33
- /**
34
- * Request function for Squeezebox server
35
- *
36
- * @param address The address of the Squeezebox server
37
- * @param port The port number, or a string of the form "ssh://password:username@hostname:port" for an SSH tunnel
38
- * @param username The username for basic authentication
39
- * @param password The password for basic authentication
40
- */
41
- function SqueezeRequest(address, port, username, password) {
42
- // FIXME URI
43
- this.address = typeof address !== 'string' ? 'localhost' : address;
44
- this.port = port !== undefined ? port : 9000;
45
- this.username = username;
46
- this.password = password;
47
- this.id = `squeezenode.${process.pid}`; // FIXME lamba seems to be 1 always add instance?
48
- this.queue = [];
49
- let client;
50
- /**
51
- * Function to handle responses
52
- *
53
- * @param err An error message
54
- * @param reply The reply
55
- * @param callback The function to call with the result
56
- */
57
- function handle(err, reply, callback) {
58
- let result = {};
59
- if (err) {
60
- result = err;
61
- result.ok = false;
62
- } else {
63
- result = reply;
64
- result.ok = true;
65
- }
66
-
67
- if (callback) {
68
- callback(result);
69
- }
70
- }
71
-
72
- // Set up to use an AWS SQS queue URL to communicate
73
- if (typeof port === 'string' && port.substr(0, 3) === 'ssh') {
74
- const { URL } = require('node:url');
75
- const turl = new URL(this.port);
76
- const surl = new URL(this.address);
77
- const fp = 9192;
78
- const Tunnel = require('tunnel-ssh');
79
- const tunnel_config = {
80
- // transport url
81
- host: turl.hostname,
82
- port: turl.port ? turl.port : 22,
83
- username: turl.username,
84
- // server url
85
- dstPort: surl.port ? surl.port : 9000,
86
- dstHost: surl.hostname,
87
- // forward url?
88
- localPort: fp,
89
- //localHost: ,
90
- keepAlive: true,
91
- };
92
- const tp = decodeURIComponent(turl.password);
93
- console.log(tp);
94
- if (tp.substr(0, 7) === 'file://') {
95
- tunnel_config['privateKey'] = require('node:fs').readFileSync(tp.substr(7));
96
- } else {
97
- tunnel_config['password'] = turl.password;
98
- }
99
- console.log(tunnel_config);
100
- this.ssh_tunnel = Tunnel(tunnel_config, function (error) {
101
- if (error) {
102
- console.log(error);
103
- }
104
- });
105
-
106
- // Use a listener to handle errors outside the callback
107
- this.ssh_tunnel.on('error', function (err) {
108
- console.error('SSH Tunnel:', err);
109
- console.log('Tunnel error');
110
- });
111
- this.address = `${surl.protocol}//localhost`;
112
- this.port = fp;
113
- console.log(surl);
114
- }
115
-
116
- if (typeof this.port === 'string' && this.port.substr(0, 6) === 'awssqs') {
117
- AWS = require('aws-sdk');
118
- this.request = request_sqs;
119
- // FIXME decode region from url
120
- this.sqs = new AWS.SQS({ region: 'us-west-2' });
121
- this.sendq = { QueueUrl: password.send, MessageGroupId: this.id };
122
- this.recvq = { QueueUrl: password.recv, WaitTimeSeconds: 0, MaxNumberOfMessages: 10 };
123
- this.reciving = true;
124
-
125
- this.sqs.receiveMessage(this.recvq, function (err, reply) {
126
- this.recvq.MaxNumberOfMessages = 1;
127
- this.recvq.WaitTimeSeconds = 20;
128
- if (reply.Messages) {
129
- let msg = reply.Messages.pop();
130
- while (msg) {
131
- const deleteParams = {
132
- QueueUrl: this.recvq.QueueUrl,
133
- ReceiptHandle: msg.ReceiptHandle,
134
- };
135
- this.sqs.deleteMessage(deleteParams, function (/* err, data */) {
136
- //
137
- });
138
- msg = reply.Messages.pop();
139
- }
140
- }
141
- request_sqs_dispatch_queue();
142
- }); //Drain Q.
143
- } else {
144
- // Use JSON RPC to communicate
145
- this.request = request_rpc;
146
-
147
- const jsonrpc =
148
- typeof this.port === 'number' ? `${this.address}:${this.port}/jsonrpc.js` : `${this.address}/jsonrpc.js`;
149
- client =
150
- this.address.substr(0, 5) === 'https'
151
- ? jayson.client.https(jsonrpc)
152
- : (client = jayson.client.http(jsonrpc));
153
- client.options.version = 1;
154
-
155
- // FIXME URL
156
- // Add a header for basic authentication if a username and password are given
157
- if (username && password) {
158
- if (!client.options.headers) {
159
- client.options.headers = {};
160
- }
161
- client.options.headers['Authorization'] = formatBasicHeader(username, password);
162
- }
163
- }
164
-
165
- /**
166
- * Request function for JSON RPC
167
- *
168
- * @param player The target player
169
- * @param params Request parameters
170
- * @param callback The function to call with the result
171
- */
172
-
173
- function request_rpc(player, params, callback) {
174
- client.request('slim.request', [player, params], this.id, function (err, reply) {
175
- handle(err, reply, callback);
176
- });
177
- }
178
-
179
- /**
180
- * Request function to use AWS SQS
181
- *
182
- * @param player The target player
183
- * @param params Request parameters
184
- * @param callback The function to call with the result
185
- */
186
-
187
- function request_sqs_dispatch(player, params, callback) {
188
- this.sendq['MessageBody'] = JSON.stringify({
189
- params: [player, params],
190
- id: this.id + process.hrtime(),
191
- version: '1.0',
192
- method: 'slim.request',
193
- }); // FIXME id not on pid but an uuid? for instrance from env?
194
- this.sendq['MessageDeduplicationId'] = this.sendq.MessageGroupId + process.hrtime();
195
- //console.log("send ",that.sendq['MessageBody']);
196
- this.sqs.sendMessage(this.sendq, function (err, data) {
197
- if (err) {
198
- handle(err, data, callback);
199
- console.error('Send Error ', err);
200
- } else {
201
- // successful response - callback for reply
202
- this.reciving = true;
203
- this.sqs.receiveMessage(this.recvq, function (err, reply) {
204
- //console.log("reply data ",reply);
205
- let message_data = {};
206
- if (reply.Messages) {
207
- //id check?
208
-
209
- message_data = reply.Messages.pop();
210
-
211
- //delete and drain?
212
-
213
- let msg = message_data;
214
- message_data = JSON.parse(message_data.Body);
215
- //console.log("reply ",message_data);
216
- while (msg) {
217
- const deleteParams = {
218
- QueueUrl: this.recvq.QueueUrl,
219
- ReceiptHandle: msg.ReceiptHandle,
220
- };
221
- // FIXME delete error
222
- this.sqs.deleteMessage(deleteParams, function (err /* , data */) {
223
- if (err) {
224
- console.error('Delete Error', err);
225
- } else {
226
- //console.log("Message Deleted", data);
227
- }
228
- });
229
- msg = reply.Messages.pop();
230
- }
231
- } else {
232
- console.warn('no msgs ', err);
233
- err = 'No reply message recvied';
234
- }
235
-
236
- handle(err, message_data, callback);
237
- request_sqs_dispatch_queue();
238
- });
239
- }
240
- });
241
- }
242
-
243
- // We need to serialise requests and responces for queue use
244
-
245
- function request_sqs(player, params, callback) {
246
- if (this.reciving) {
247
- this.queue.push([player, params, callback]);
248
- } else {
249
- request_sqs_dispatch(player, params, callback);
250
- }
251
- }
252
-
253
- function request_sqs_dispatch_queue() {
254
- const args = this.queue.pop();
255
- if (args) {
256
- request_sqs_dispatch.apply(null, args);
257
- } else {
258
- this.reciving = false;
259
- }
260
- }
261
- }
262
-
263
- /**
264
- * Function to format the header for basic authentication.
265
- */
266
-
267
- function formatBasicHeader(username, password) {
268
- const tok = `${username}:${password}`;
269
- const hash = new Buffer.from(tok).toString('base64');
270
- return `Basic ${hash}`;
271
- }
272
-
273
- module.exports = SqueezeRequest;
@@ -1,352 +0,0 @@
1
- /*
2
- The MIT License (MIT)
3
-
4
- Copyright (c) 2013 Piotr Raczynski, pio[dot]raczynski[at]gmail[dot]com
5
-
6
- Permission is hereby granted, free of charge, to any person obtaining a copy
7
- of this software and associated documentation files (the "Software"), to deal
8
- in the Software without restriction, including without limitation the rights
9
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- copies of the Software, and to permit persons to whom the Software is
11
- furnished to do so, subject to the following conditions:
12
-
13
- The above copyright notice and this permission notice shall be included in all
14
- copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- SOFTWARE.
23
- */
24
-
25
- const inherits = require('super');
26
- const fs = require('node:fs');
27
- const SqueezeRequest = require(`${__dirname}/squeezerequest`);
28
- const SqueezePlayer = require(`${__dirname}/squeezeplayer`);
29
-
30
- /**
31
- * Create a SqueezeServer object
32
- *
33
- * @param address The URL of the server
34
- * @param port The port that the server listens on
35
- * @param username The username for authentication
36
- * @param password The password for authentication
37
- * @param sa A flag to skip apps
38
- * @param sp A flag to skip players
39
- */
40
- function SqueezeServer(address, port, username, password, sa, sp) {
41
- SqueezeServer.super_.apply(this, arguments);
42
- const defaultPlayer = '00:00:00:00:00:00';
43
- this.players = [];
44
- this.apps = [];
45
- const subs = {};
46
-
47
- /**
48
- * Subscribe to an event on a channel
49
- *
50
- * @param channel The channel that received the event
51
- * @param sub The callback for the event
52
- */
53
-
54
- this.on = function (channel, sub) {
55
- subs[channel] = subs[channel] || [];
56
- subs[channel].push(sub);
57
- };
58
-
59
- /**
60
- * Send an event.
61
- *
62
- * @param channel The even channel
63
- */
64
-
65
- this.emit = function (channel) {
66
- const args = [].slice.call(arguments, 1);
67
- for (const sub in subs[channel]) {
68
- subs[channel][sub].apply(void 0, args);
69
- }
70
- };
71
-
72
- /**
73
- * Method to the the number of players.
74
- *
75
- * @param callback The function to call with the result.
76
- */
77
-
78
- this.getPlayerCount = function (callback) {
79
- this.request(defaultPlayer, ['player', 'count', '?'], callback);
80
- };
81
-
82
- /**
83
- * Method to get the ID of a player given it's index
84
- *
85
- * @param index The index of the player to get the ID for
86
- * @param callback The function to call with the result.
87
- */
88
-
89
- this.getPlayerId = function (index, callback) {
90
- this.request(defaultPlayer, ['player', 'id', index, '?'], callback);
91
- };
92
-
93
- /**
94
- * Method to get the IP address of a player
95
- *
96
- * @param playerId The ID or index of the player
97
- * @param callback The function to call with the result.
98
- */
99
-
100
- this.getPlayerIp = function (playerId, callback) {
101
- this.request(defaultPlayer, ['player', 'ip', playerId, '?'], callback);
102
- };
103
-
104
- /**
105
- * Method to get the name of a player.
106
- *
107
- * @param playerId The ID or index of the player
108
- * @param callback The function to call with the result.
109
- */
110
-
111
- this.getPlayerName = function (playerId, callback) {
112
- this.request(defaultPlayer, ['player', 'name', playerId, '?'], callback);
113
- };
114
-
115
- /**
116
- * Get a list of the synchronization group members
117
- *
118
- * @param callback The function to call with the result.
119
- */
120
-
121
- this.getSyncGroups = function (callback) {
122
- this.request(defaultPlayer, ['syncgroups', '?'], callback);
123
- };
124
-
125
- /**
126
- * Get a list of the apps installed in the server
127
- *
128
- * @param callback The function to call with the result.
129
- */
130
-
131
- this.getApps = function (callback) {
132
- this.request(defaultPlayer, ['apps', 0, 100], callback);
133
- };
134
-
135
- //
136
-
137
- /**
138
- * Get the content of a music folder.
139
- *
140
- * @param folderId The ID of the folder to get. Pass 0 or empty string "" to display root of music folder
141
- * @param callback The function to call with the result.
142
- */
143
-
144
- this.musicfolder = function (folderId, callback) {
145
- this.request(defaultPlayer, ['musicfolder', 0, 100, `folder_id:${folderId}`], callback);
146
- };
147
-
148
- /**
149
- * Get a information about the players.
150
- *
151
- * @param callback The function to call with the result.
152
- */
153
-
154
- this.getPlayers = callback => {
155
- this.request(defaultPlayer, ['players', 0, 100], function (reply) {
156
- if (reply.ok) {
157
- reply.result = reply.result.players_loop;
158
- }
159
- callback(reply);
160
- });
161
- };
162
-
163
- /**
164
- * Get a list of the artists from the server
165
- *
166
- * @param callback The callback to call with the result
167
- * @param limit The maximum number of results
168
- */
169
-
170
- this.getArtists = (callback, limit) => {
171
- this.request(defaultPlayer, ['artists', 0, limit], function (reply) {
172
- if (reply.ok) {
173
- reply.result = reply.result.artists_loop;
174
- }
175
- callback(reply);
176
- });
177
- };
178
-
179
- /**
180
- * Get a list of the albums from the server
181
- *
182
- * @param callback The callback to call with the result
183
- * @param limit The maximum number of results
184
- */
185
-
186
- this.getAlbums = (callback, limit) => {
187
- this.request(defaultPlayer, ['albums', 0, limit], function (reply) {
188
- if (reply.ok) {
189
- reply.result = reply.result.albums_loop;
190
- }
191
- callback(reply);
192
- });
193
- };
194
-
195
- /**
196
- * Get a list of the genre's from the server
197
- *
198
- * @param callback The callback to call with the result
199
- * @param limit The maximum number of results
200
- */
201
-
202
- this.getGenres = (callback, limit) => {
203
- this.request(defaultPlayer, ['genres', 0, limit], function (reply) {
204
- if (reply.ok) {
205
- reply.result = reply.result.genres_loop;
206
- }
207
- callback(reply);
208
- });
209
- };
210
-
211
- /**
212
- * Get a 'info' list from the server
213
- *
214
- * @param callback The callback to call with the result
215
- * @param limit The maximum number of results
216
- * @param slot The query to make to the server [genres, albums, artists, playlists ]
217
- */
218
-
219
- this.getInfo = (callback, limit, slot) => {
220
- this.request(defaultPlayer, [slot, 0, limit], function (reply) {
221
- if (reply.ok) {
222
- reply.result = reply.result[`${slot}_loop`];
223
- }
224
- callback(reply);
225
- });
226
- };
227
-
228
- this.registerPlayers = players => {
229
- for (const pl in players) {
230
- if (!this.players[players[pl].playerid]) {
231
- // player not on the list
232
- this.players[players[pl].playerid] = new SqueezePlayer(
233
- players[pl].playerid,
234
- players[pl].name,
235
- this.address,
236
- this.port,
237
- this.username,
238
- this.password,
239
- );
240
- }
241
- }
242
- };
243
-
244
- /**
245
- * Get Player oject for name, needs the players registred and normisles names with a lc search removeving puntuation
246
- *
247
- * @param name string
248
- * @param only reten the one player if only one
249
- */
250
- this.findPlayerObjectByName = function (name, only) {
251
- name = this.normalizePlayer(name);
252
-
253
- // Look for the player in the players list that matches the given name. Then return the corresponding player object
254
- // from the squeezeserver stored by the player's id
255
-
256
- for (const id in this.players) {
257
- if (
258
- this.normalizePlayer(this.players[id].name) === name || // name matches the requested player
259
- (name === '' && only && this.players.length === 1) // name is undefined and there's only one player,
260
- // so assume that's the one we want.
261
- ) {
262
- return this.players[id];
263
- }
264
- }
265
- return undefined;
266
- };
267
-
268
- /**
269
- * Do any necessary clean up of player names
270
- *
271
- * @param playerName The name of the player to clean up
272
- * @param filter optional fn(str) returns str
273
- * @returns The normalized player name
274
- */
275
-
276
- this.normalizePlayer = function (playerName) {
277
- playerName || (playerName = ''); // protect against `playerName` being undefined
278
- playerName = playerName.replace('-', ' ');
279
- playerName = playerName.replace(' ', ' ');
280
- playerName = playerName.replace(' ', ' ');
281
- playerName = playerName.toLowerCase(playerName);
282
-
283
- return playerName;
284
- };
285
-
286
- /**
287
- * Find out if we can contact the server and get some basic information
288
- *
289
- * @param skipApps A flag to skip getting information about the apps
290
- */
291
-
292
- this.register = function (skipApps, skipPlayers) {
293
- if (!skipPlayers) {
294
- // Get the list of players from the server
295
- this.getPlayers(reply => {
296
- // Process the player information and create Player objects for each one
297
- if (reply.ok) {
298
- this.registerPlayers(reply.result);
299
- }
300
-
301
- // Send a signal that we are done
302
- if (skipApps) {
303
- this.emit('register', reply, undefined);
304
- } else {
305
- this.emit('registerPlayers', reply);
306
- }
307
- });
308
- }
309
-
310
- if (!skipApps) {
311
- // Once the players have been obtained, request a list of the apps
312
- this.on('registerPlayers', reply => {
313
- this.getApps(areply => {
314
- if (areply.ok) {
315
- const apps = areply.result.appss_loop;
316
- const dir = `${__dirname}/`;
317
- fs.readdir(dir, (err, files) => {
318
- files.forEach(file => {
319
- const fil = file.substr(0, file.lastIndexOf('.'));
320
- for (const pl in apps) {
321
- if (fil === apps[pl].cmd) {
322
- const app = require(dir + file);
323
- this.apps[apps[pl].cmd] = new app(
324
- defaultPlayer,
325
- apps[pl].name,
326
- apps[pl].cmd,
327
- this.address,
328
- this.port,
329
- this.username,
330
- this.password,
331
- );
332
- /* workaround, app needs existing player id so first is used here */
333
- }
334
- }
335
- });
336
-
337
- this.emit('register', reply, areply);
338
- });
339
- } else {
340
- this.emit('register', reply, areply);
341
- }
342
- });
343
- });
344
- }
345
- };
346
-
347
- this.register(sa, sp);
348
- }
349
-
350
- inherits(SqueezeServer, SqueezeRequest);
351
-
352
- module.exports = SqueezeServer;