« get me outta code hell

play.js - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/play.js
blob: 8833c89e054f063e3857735804ce825e8ede2f3f (plain)
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
// TODO: Get `avconv` working. Oftentimes `play` won't be able to play
//       some tracks due to an unsupported format; we'll need to use
//       `avconv` to convert them (to WAV).
//       (Done!)
//
// TODO: Get `play` working.
//       (Done!)
//
// TODO: Get play-next working; probably just act like a shuffle. Will
//       need to keep an eye out for the `play` process finishing.
//       (Done!)
//
// TODO: Preemptively download and process the next track, while the
//       current one is playing, to eliminate the silent time between
//       tracks.
//       (Done!)
//
// TODO: Delete old tracks! Since we aren't overwriting files, we
//       need to manually delete files once we're done with them.
//       (Done!)
//
// TODO: Clean up on SIGINT.
//
// TODO: Get library filter path from stdin.
//       (Done!)
//
// TODO: Show library tree. Do this AFTER filtering, so that people
//       can e.g. see all albums by a specific artist.
//       (Done!)
//
// TODO: Ignore .DS_Store.
//       (Done!)
//
// TODO: Have a download timeout, somehow.
//
// TODO: Fix the actual group format. Often times we get single-letter
//       files being downloaded (which don't exist); I'm guessing that's
//       related to folder names (which are just strings, not title-href
//       arrays) still being in the group array. (Update: that's defin-
//       itely true; 'Saucey Sounds'[0] === 'S', and 'Unofficial'[0]
//       === 'U', which are the two "files" it crashes on while playing
//       -g 'Jake Chudnow'.)
//       (Done!)
//
// TODO: A way to exclude a specific group path.
//       (Done!)
//
// TODO: Better argv handling.
//       (Done!)
//
// TODO: Option to include a specific path from the source playlist.
//       (Done!)
//
// TODO: Make a playlist generator that parses http://billwurtz.com
//       instrumentals.html.
//       (Done!)
//
// TODO: Make crawl-itunes.js a bit more general, more command-line
//       friendly (i.e. don't require editing the script itself), and
//       make it use the getHTMLLinks function defined in the new
//       crawl-links.js script.
//       (Done!)
//
// TODO: Play-in-order track picker.
//       (Done!)

'use strict'

const fs = require('fs')
const util = require('util')
const { spawn } = require('child_process')

const fetch = require('node-fetch')
const sanitize = require('sanitize-filename')

const writeFile = util.promisify(fs.writeFile)
const readFile = util.promisify(fs.readFile)

function promisifyProcess(proc, showLogging = true) {
	return new Promise((resolve, reject) => {
		if (showLogging) {
			proc.stdout.pipe(process.stdout)
			proc.stderr.pipe(process.stderr)
		}

		proc.on('exit', code => {
			if (code === 0) {
				resolve()
			} else {
				console.error('Process failed!', proc.spawnargs)
				reject(code)
			}
		})
	})
}

function flattenPlaylist(playlist) {
	const groups = playlist.filter(x => Array.isArray(x[1]))
	const nonGroups = playlist.filter(x => x[1] && !(Array.isArray(x[1])))
	return groups.map(g => flattenPlaylist(g[1]))
		.reduce((a, b) => a.concat(b), nonGroups)
}

function convert(fromFile, toFile) {
	const avconv = spawn('avconv', ['-y', '-i', fromFile, toFile])
	return promisifyProcess(avconv, false)
}

function playFile(file) {
	const play = spawn('play', [file])
	return promisifyProcess(play)
}

function makeOrderedPlaylistPicker(playlist) {
	const allSongs = flattenPlaylist(playlist)
	let index = 0

	return function() {
		if (index < allSongs.length) {
			const picked = allSongs[index]
			index++
			return picked
		} else {
			return null
		}
	}
}

function makeShufflePlaylistPicker(playlist) {
	const allSongs = flattenPlaylist(playlist)

	return function() {
		const index = Math.floor(Math.random() * allSongs.length)
		const picked = allSongs[index]
		return picked
	}
}

async function loopPlay(fn) {
	// Looping play function. Takes one argument, the "pick" function,
	// which returns a track to play. Preemptively downloads the next
	// track while the current one is playing for seamless continuation
	// from one song to the next. Stops when the result of the pick
	// function is null (or similar).

	async function downloadNext() {
		const picked = fn()

		if (picked == null) {
			return false
		}

		const [ title, href ] = picked
		console.log(`Downloading ${title}..\n${href}`)

		const wavFile = `.${sanitize(title)}.wav`

		const res = await fetch(href)
		const buffer = await res.buffer()
		await writeFile('./.temp-track', buffer)

		try {
			await convert('./.temp-track', wavFile)
		} catch(err) {
			console.warn('Failed to convert ' + title)
			console.warn('Selecting a new track\n')

			return await downloadNext()
		}

		await fs.unlink('./.temp-track')

		return wavFile
	}

	let wavFile = await downloadNext()

	while (wavFile) {
		const nextPromise = downloadNext()
		await playFile(wavFile)
		await fs.unlink(wavFile)
		wavFile = await nextPromise
	}
}

function filterPlaylistByPathString(playlist, pathString) {
	return filterPlaylistByPath(playlist, parsePathString(pathString))
}

function filterPlaylistByPath(playlist, pathParts) {
	// Note this can be used as a utility function, rather than just as
	// a function for use by the argv-handler!

	let cur = pathParts[0]

	const match = playlist.find(g => g[0] === cur || g[0] === cur + '/')

	if (match) {
		const groupContents = match[1]
		if (pathParts.length > 1) {
			const rest = pathParts.slice(1)
			return filterPlaylistByPath(groupContents, rest)
		} else {
			return match
		}
	} else {
		console.warn(`Not found: "${cur}"`)
		return playlist
	}
}

function ignoreGroupByPathString(playlist, pathString) {
	const pathParts = parsePathString(pathString)
	return ignoreGroupByPath(playlist, pathParts)
}

function ignoreGroupByPath(playlist, pathParts) {
	// TODO: Ideally this wouldn't mutate the given playlist.

	const groupToRemove = filterPlaylistByPath(playlist, pathParts)

	const parentPath = pathParts.slice(0, pathParts.length - 1)
	let parent

	if (parentPath.length === 0) {
		parent = playlist
	} else {
		parent = filterPlaylistByPath(playlist, pathParts.slice(0, -1))
	}

	const index = parent.indexOf(groupToRemove)

	if (index >= 0) {
		parent.splice(index, 1)
	} else {
		console.error(
			'Group ' + pathParts.join('/') + ' doesn\'t exist, so we can\'t ' +
			'explicitly ignore it.'
		)
	}
}

function getPlaylistTreeString(playlist, showTracks = false) {
	function recursive(group) {
		const groups = group.filter(x => Array.isArray(x[1]))
		const nonGroups = group.filter(x => x[1] && !(Array.isArray(x[1])))

		const childrenString = groups.map(g => {
			const groupString = recursive(g[1])

			if (groupString) {
				const indented = groupString.split('\n').map(l => '| ' + l).join('\n')
				return '\n' + g[0] + '\n' + indented
			} else {
				return g[0]
			}
		}).join('\n')

		const tracksString = (showTracks ? nonGroups.map(g => g[0]).join('\n') : '')

		if (tracksString && childrenString) {
			return tracksString + '\n' + childrenString
		} else if (childrenString) {
			return childrenString
		} else if (tracksString) {
			return tracksString
		} else {
			return ''
		}
	}

	return recursive(playlist)
}

function parsePathString(pathString) {
	const pathParts = pathString.split('/')
	return pathParts
}

async function processArgv(argv, handlers) {
	let i = 0

	async function handleOpt(opt) {
		if (opt in handlers) {
			await handlers[opt]({
				argv, index: i,
				nextArg: function() {
					i++
					return argv[i]
				},
				alias: function(optionToRun) {
					handleOpt(optionToRun)
				}
			})
		} else {
			console.warn('Option not understood: ' + opt)
		}
	}

	for (; i < argv.length; i++) {
		const cur = argv[i]
		if (cur.startsWith('-')) {
			const opt = cur.slice(1)
			await handleOpt(opt)
		}
	}
}

readFile('./playlist.json', 'utf-8')
	.then(plText => JSON.parse(plText))
	.then(async playlist => {
		let sourcePlaylist = playlist
		let curPlaylist = playlist

		let pickerType = 'shuffle'

		// WILL play says whether the user has forced playback via an argument.
		// SHOULD play says whether the program has automatically decided to play
		// or not, if the user hasn't set WILL play.
		let shouldPlay = true
		let willPlay = null

		await processArgv(process.argv, {
			'-open': async function(util) {
				// --open <file>  (alias: -o)
				// Opens a separate playlist file.
				// This sets the source playlist.

				const openedPlaylist = JSON.parse(await readFile(util.nextArg(), 'utf-8'))
				sourcePlaylist = openedPlaylist
				curPlaylist = openedPlaylist
			},

			'o': util => util.alias('-open'),

			'-clear': function(util) {
				// --clear  (alias: -c)
				// Clears the active playlist. This does not affect the source
				// playlist.

				curPlaylist = []
			},

			'c': util => util.alias('-clear'),

			'-keep': function(util) {
				// --keep <groupPath>  (alias: -k)
				// Keeps a group by loading it from the source playlist into the
				// active playlist. This is usually useful after clearing the
				// active playlist; it can also be used to keep a subgroup when
				// you've ignored an entire parent group, e.g. `-i foo -k foo/baz`.

				const pathString = util.nextArg()
				const group = filterPlaylistByPathString(sourcePlaylist, pathString)
				curPlaylist.push(group)
			},

			'k': util => util.alias('-keep'),

			'-ignore': function(util) {
				// --ignore <groupPath>  (alias: -i)
				// Filters the playlist so that the given path is removed.

				const pathString = util.nextArg()
				console.log('Ignoring path: ' + pathString)
				ignoreGroupByPathString(curPlaylist, pathString)
			},

			'i': util => util.alias('-ignore'),

			'-list-groups': function(util) {
				// --list-groups  (alias: -l, --list)
				// Lists all groups in the playlist.

				console.log(getPlaylistTreeString(curPlaylist))

				// If this is the last item in the argument list, the user probably
				// only wants to get the list, so we'll mark the 'should run' flag
				// as false.
				if (util.index === util.argv.length - 1) {
					shouldPlay = false
				}
			},

			'-list': util => util.alias('-list-groups'),
			'l': util => util.alias('-list-groups'),

			'-list-all': function(util) {
				// --list-all  (alias: --list-tracks, -L)
				// Lists all groups and tracks in the playlist.

				console.log(getPlaylistTreeString(curPlaylist, true))

				// As with -l, if this is the last item in the argument list, we
				// won't actually be playing the playlist.
				if (util.index === util.argv.length - 1) {
					shouldPlay = false
				}
			},

			'-list-tracks': util => util.alias('-list-all'),
			'L': util => util.alias('-list-all'),

			'-play': function(util) {
				// --play  (alias: -p)
				// Forces the playlist to actually play.

				willPlay = true
			},

			'p': util => util.alias('-play'),

			'-no-play': function(util) {
				// --no-play  (alias: -np)
				// Forces the playlist not to play.

				willPlay = false
			},

			'np': util => util.alias('-no-play'),

			'-debug-list': function(util) {
				// --debug-list
				// Prints out the JSON representation of the active playlist.

				console.log(JSON.stringify(curPlaylist, null, 2))
			},

			'-picker': function(util) {
				// --picker <shuffle|ordered>
				// Selects the mode that the song to play is picked.
				// This should be used after finishing modifying the active
				// playlist.

				pickerType = util.nextArg()
			}
		})

		if (willPlay || (willPlay === null && shouldPlay)) {
			let picker
			if (pickerType === 'shuffle') {
				console.log('Using shuffle picker')
				picker = makeShufflePlaylistPicker(curPlaylist)
			} else if (pickerType === 'ordered') {
				console.log('Using ordered picker')
				picker = makeOrderedPlaylistPicker(curPlaylist)
			} else {
				console.error('Invalid picker type: ' + pickerType)
			}

			return loopPlay(picker)
		} else {
			return curPlaylist
		}
	})
	.catch(err => console.error(err))