-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·500 lines (452 loc) · 15.1 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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#!/usr/bin/env node
var _ = require('underscore');
var request = require('request');
var FileCookieStore = require('tough-cookie-filestore');
var fs = require('fs');
var Duration = require('duration');
var mkdirp = require('mkdirp');
var root = process.env.HOME + '/.nodeplayer-client';
mkdirp.sync(root + '/temp');
mkdirp.sync(root + '/playlists');
var tempResultsPath = root + '/temp/searchresults.json';
var nodeplayerConfig = require('nodeplayer-config');
var coreConfig = nodeplayerConfig.getConfig();
var defaultConfig = require('./default-config.js');
var config = require('nodeplayer-config').getConfig('client', defaultConfig);
// enable cookies
fs.openSync(nodeplayerConfig.getConfigDir() + '/client-cookies.json', 'a');
var j = request.jar(new FileCookieStore(
nodeplayerConfig.getConfigDir() + '/client-cookies.json'));
request = request.defaults({jar: j});
var tlsOpts = {
key: config.key ? fs.readFileSync(config.key) : undefined,
cert: config.cert ? fs.readFileSync(config.cert) : undefined,
ca: config.ca ? fs.readFileSync(config.ca) : undefined,
rejectUnauthorized: config.rejectUnauthorized
};
var usageText = '';
usageText += 'show and manipulate the nodeplayer queue.\n\n';
usageText += 'commands\n';
usageText += '========\n';
usageText += 'search for songs:\n';
usageText += ' -l show queue (default action)\n';
usageText += ' -p list playlists\n';
usageText += ' -p [ID] list contents of playlist ID\n';
usageText += ' -s [QUERY] perform search matching QUERY\n';
usageText += 'manipulate playback/queue:\n';
usageText += ' -a ID [POS] append song with ID\n';
usageText += ' -d ID delete song with ID\n';
usageText += ' -m FROM TO [CNT] move CNT songs FROM pos TO pos\n';
usageText += ' -g [CNT] skip CNT songs, can be negative to go back\n';
usageText += ' -k [POS] seek playback to POS seconds, left out to resume\n';
usageText += ' -u pause playback\n';
usageText += ' -z shuffle queue\n';
usageText += 'misc:\n';
usageText += ' -n show now playing song\n';
usageText += ' -w FILENAME write current playlist into FILENAME\n';
usageText += ' -r ID recalculate HMAC in playlist with ID\n';
usageText += ' -i ID insert now playing into playlist with ID\n';
usageText += ' -t authenticate to passport\n';
usageText += ' -h show this help and quit\n';
var yargs = require('yargs')
.boolean('s');
var argv = yargs.argv;
if(argv.h) {
console.log(usageText);
process.exit(0);
}
var printSong = function(song, id) {
if(!_.isUndefined(id)) {
process.stdout.write(' ' + id + ': ');
}
console.log(song.artist + ' - ' + song.title + ' (' + song.album + ')');
};
var onexit = function() {
process.stdout.write('\x1b[?25h'); // enable cursor
process.exit();
};
var parseRange = function(str) {
var res = str.match(/(\d*)\.\.(\d*)/);
if(!res)
return null;
var range = [];
range[0] = res[1] || 0;
range[1] = res[2] || 9999999999999;
return range;
};
var url = (config.tls ? 'https://' : 'http://') + config.hostname + ':' + config.port;
if (argv.h) {
console.log(usageText);
} else if (argv.t) {
request.post({
url: url + '/login',
json: {
username: config.username,
password: config.password
},
agentOptions: tlsOpts
}, function(err, res, body) {
if(!err) {
console.log('success: ' + body);
} else {
console.log('error: ' + err);
}
});
} else if (argv.s) {
request.post({
url: url + '/search',
json: {terms: argv._.join(' ')},
agentOptions: tlsOpts
}, function(err, res, body) {
if(!err) {
var results = [];
var id = 0;
_.each(body, function(backend, backendName) {
console.log(backendName + ':');
_.each(backend.songs, function(song) {
printSong(song, id);
results.push(song);
id++;
});
});
fs.writeFileSync(tempResultsPath, JSON.stringify(results, undefined, 4));
} else {
console.log('error: ' + err);
}
});
} else if (!_.isUndefined(argv.g)) {
// "goto"
if(argv.g === true)
argv.g = 1;
request.post({
url: url + '/playctl',
json: {
action: 'skip',
cnt: argv.g
},
agentOptions: tlsOpts
}, function(err, res, body) {
console.log(body);
});
} else if (!_.isUndefined(argv.d)) {
var cnt = 1;
var range;
var start = argv.d;
if(argv.d === true)
start = 0;
if(_.isString(argv.d))
range = parseRange(argv.d);
if(range) {
start = range[0];
cnt = range[1] - range[0] + 1;
}
request.del({
url: url + '/queue/del/' + start,
json: {
cnt: cnt
},
agentOptions: tlsOpts
}, function(err, res, songs) {
console.log("deleted songs:");
_.each(songs, function(song) {
printSong(song);
});
});
} else if (!_.isUndefined(argv.m)) {
request.post({
url: url + '/queue/move/' + argv.m,
json: {
to: argv._[0],
cnt: argv._[1]
},
agentOptions: tlsOpts
}, function(err, res, body) {
if(!err) {
console.log('songs moved:');
_.each(body, function(song) {
printSong(song);
});
} else {
console.log('error: ' + err);
}
});
} else if (!_.isUndefined(argv.a)) {
if(fs.existsSync(tempResultsPath)) {
var tempResults = require(tempResultsPath);
var matches = [];
var range;
if(_.isString(argv.a))
range = parseRange(argv.a);
if(argv.a === true) {
// entire playlist
matches = tempResults;
} else if(range) {
// x..y range
matches = tempResults.filter(function(song, i) {
return (i >= range[0] && i <= range[1]);
});
} else {
// by id
matches = [tempResults[argv.a]];
}
// TODO: check if host is running partyplay before doing this?
for(var i = 0; i < matches.length; i++) {
matches[i].userID = 'nodeplayer-client';
}
request.post({
url: url + '/queue/add',
json: {
songs: matches,
pos: argv._[0]
},
agentOptions: tlsOpts
}, function(err, res, body) {
if(!err) {
console.log('songs queued:');
_.each(matches, function(song) {
printSong(song);
});
} else {
console.log('error: ' + err);
}
});
} else {
console.log('no search results');
}
} else if(!_.isUndefined(argv.p)) {
// without parameters: list all playlists
if(argv.p === true) {
var playlists = fs.readdirSync(root + '/playlists');
playlists.sort();
var id = 0;
_.each(playlists, function(playlistName) {
console.log(' ' + id + ': ' + playlistName);
id++;
});
} else {
var playlists = fs.readdirSync(root + '/playlists');
playlists.sort();
// loop over playlists to find the requested one
var playlist;
var id = 0;
_.each(playlists, function(playlistName) {
if(id === argv.p) {
playlist = require(root + '/playlists/' + playlistName);
}
id++;
});
// loop over songs (in reverse order) and print them
playlist.reverse();
id = 0;
_.each(playlist, function(song) {
printSong(song, id);
id++;
});
// store song list
fs.writeFileSync(tempResultsPath, JSON.stringify(playlist, undefined, 4));
}
} else if(argv.n) {
var socket = require('socket.io-client')((config.tls ? 'https://' : 'http://') + config.hostname + ':' + config.port, tlsOpts);
var zpad = require('zpad');
var npInterval = null;
var playbackInfo = {};
var playbackInfoTime = 0;
process.stdin.setRawMode(true); // hide input
process.stdout.write('\x1b[?25l'); // hide cursor
process.on('SIGINT', onexit);
// q or ctrl-c pressed: run onexit
process.stdin.on('data', function(key) {
if(key == 'q' || key == '\u0003') onexit();
});
var printSongTime = function() {
process.stdout.write('\r');
process.stdout.write('\033[2K');
if(!_.isEmpty(playbackInfo) && playbackInfo.playbackStart) {
var curTime = new Date().getTime();
var position = new Duration(new Date(playbackInfoTime), new Date(curTime + (playbackInfo.position || 0)));
var duration = new Duration(new Date(curTime), new Date(curTime + parseInt(playbackInfo.duration)));
process.stdout.write('[');
process.stdout.write(String(position.minutes) + ':' + zpad(position.seconds % 60, 2));
process.stdout.write('/');
process.stdout.write(String(duration.minutes) + ':' + zpad(duration.seconds % 60, 2));
process.stdout.write(']');
} else {
process.stdout.write('[0:00/0:00]');
}
};
socket.on('playback', function(newPlaybackInfo) {
playbackInfo = newPlaybackInfo;
playbackInfoTime = new Date().getTime();
});
socket.on('queue', function(queue) {
if(npInterval)
clearInterval(npInterval);
var nowPlaying = queue[0];
queue.shift();
queue.reverse();
process.stdout.write('\u001B[2J\u001B[0;0f'); // clear terminal
var id = queue.length; // note we already shifted nowPlaying out
_.each(queue, function(song) {
printSong(song, id);
id--;
});
console.log('--- Queue ---\n');
process.stdout.write('Now playing: ');
if(nowPlaying)
printSong(nowPlaying);
if(queue.length || nowPlaying) {
npInterval = setInterval(function() {
printSongTime();
}, 1000);
}
printSongTime();
});
} else if(_.isString(argv.w)) {
request.get({
url: url + '/queue',
agentOptions: tlsOpts
}, function(err, res, body) {
if(err) {
console.log(err);
return;
}
if(body) {
var queue = body;
// TODO: filter out unneeded song properties
fs.writeFileSync(root + '/playlists/' + argv.w + '.json', JSON.stringify(queue, undefined, 4));
console.log('playlist written into ' + argv.w + '.json');
}
});
} else if(!_.isUndefined(argv.i)) {
request.get({
url: url + '/queue',
agentOptions: tlsOpts
}, function(err, res, body) {
if(err) {
console.log(err);
return;
}
if(body) {
var queue = JSON.parse(body);
var song = queue.shift();
var playlists = fs.readdirSync(root + '/playlists');
// loop over playlists to find the requested one
var playlist;
var playlistPath;
var id = 0;
_.each(playlists, function(playlistName) {
if(id === argv.i) {
playlistPath = root + '/playlists/' + playlistName;
playlist = require(playlistPath);
}
id++;
});
playlist.unshift(song);
// store song list
// TODO: filter out unneeded song properties
fs.writeFileSync(playlistPath, JSON.stringify(playlist, undefined, 4));
}
});
} else if(argv.u) {
request.post({
url: url + '/playctl',
json: {
action: 'pause'
},
agentOptions: tlsOpts
}, function(err, res, body) {
console.log(body);
});
} else if(!_.isUndefined(argv.k)) {
var pos;
if(argv.k !== true)
pos = argv.k * 1000;
request.post({
url: url + '/playctl',
json: {
action: 'play',
position: pos
},
agentOptions: tlsOpts
}, function(err, res, body) {
console.log(body);
});
} else if(!_.isUndefined(argv.r)) {
var crypto = require('crypto');
var key = fs.readFileSync(config.verifyMac.key);
var derivedKey = crypto.pbkdf2Sync(key, key, config.verifyMac.iterations, config.verifyMac.keyLen);
var calculateMac = function(str) {
var hmac = crypto.createHmac(config.verifyMac.algorithm, derivedKey);
hmac.update(str);
return hmac.digest('hex');
};
var getSongHmac = function(song) {
song.album = (song.album || "");
song.artist = (song.artist || "");
song.title = (song.title || "");
return calculateMac(
song.album.replace('|', '') + '|' +
song.artist.replace('|', '') + '|' +
song.title.replace('|', '') + '|' +
song.backendName.replace('|', '') + '|' +
song.duration.toString().replace('|', '') + '|' +
song.format.replace('|', '') + '|' +
song.songID.replace('|', '') + '|'
);
};
var playlists = fs.readdirSync(root + '/playlists');
playlists.sort();
// loop over playlists to find the requested one
var playlist;
var playlistPath;
var id = 0;
_.each(playlists, function(playlistName) {
if(id === argv.r) {
playlist = require(root + '/playlists/' + playlistName);
playlistPath = root + '/playlists/' + playlistName;
}
id++;
});
if(!playlist) {
console.log('no playlist found');
return;
}
// loop over songs and fix hmac
for(var song in playlist) {
playlist[song].hmac = getSongHmac(playlist[song]);
}
// store playlist
fs.writeFileSync(playlistPath, JSON.stringify(playlist, undefined, 4));
console.log('wrote playlist with recalculated HMACs: ' + playlistPath);
} else if(argv.z) {
request.post({
url: url + '/playctl',
json: {
action: 'shuffle'
},
agentOptions: tlsOpts
}, function(err, res, body) {
console.log(body);
});
} else {
request.get({
url: url + '/queue',
agentOptions: tlsOpts
}, function(err, res, body) {
if(err) {
console.log(err);
return;
}
console.log('Queue:');
if(body) {
var queue = JSON.parse(body);
queue.reverse();
var id = queue.length - 1;
_.each(queue, function(song) {
printSong(song, id);
id--;
});
}
});
}
// TODO: replace a lot of _.each() with _.find() or similar to prevent unnecessary loops