« get me outta code hell

play.js « src - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/play.js
blob: db7088c0d58209a19a65f4af9783db78548f954a (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
#!/usr/bin/env node

'use strict'

const { promisify } = require('util')
const clone = require('clone')
const fs = require('fs')
const fetch = require('node-fetch')
const commandExists = require('./command-exists')
const pickers = require('./pickers')
const loopPlay = require('./loop-play')
const processArgv = require('./process-argv')
const processSmartPlaylist = require('./smart-playlist')

const {
  filterPlaylistByPathString, removeGroupByPathString, getPlaylistTreeString,
  updatePlaylistFormat
} = require('./playlist-utils')

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

function downloadPlaylistFromURL(url) {
  return fetch(url).then(res => res.text())
}

function downloadPlaylistFromLocalPath(path) {
  return readFile(path)
}

function downloadPlaylistFromOptionValue(arg) {
  // TODO: Verify things!
  if (arg.startsWith('http://') || arg.startsWith('https://')) {
    return downloadPlaylistFromURL(arg)
  } else {
    return downloadPlaylistFromLocalPath(arg)
  }
}

function clearConsoleLine() {
  process.stdout.write('\x1b[1K\r')
}

async function determineDefaultPlayer() {
  if (await commandExists('mpv')) {
    return 'mpv'
  } else if (await commandExists('play')) {
    return 'play'
  } else {
    return null
  }
}

async function main(args) {
  let sourcePlaylist = null
  let activePlaylist = null

  let pickerType = 'shuffle'
  let playerCommand = await determineDefaultPlayer()
  let playOpts = []

  // 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

  async function openPlaylist(arg, silent = false) {
    let playlistText

    if (!silent) {
      console.log("Opening playlist from: " + arg)
    }

    try {
      playlistText = await downloadPlaylistFromOptionValue(arg)
    } catch(err) {
      if (!silent) {
        console.error("Failed to open playlist file: " + arg)
        console.error(err)
      }

      return false
    }

    const openedPlaylist = updatePlaylistFormat(JSON.parse(playlistText))

    // We also want to de-smart-ify (stupidify? - simplify?) the playlist.
    const processedPlaylist = await processSmartPlaylist(openedPlaylist)

    // The active playlist is a clone of the source playlist; after all it's
    // quite possible we'll be messing with the value of the active playlist,
    // and we don't want to reflect those changes in the source playlist.
    sourcePlaylist = processedPlaylist
    activePlaylist = clone(processedPlaylist)

    processArgv(processedPlaylist.options, optionFunctions)
  }

  function requiresOpenPlaylist() {
    if (activePlaylist === null) {
      throw new Error(
        "This action requires an open playlist - try --open (file)"
      )
    }
  }

  const optionFunctions = {
    '-help': function(util) {
      // --help  (alias: -h, -?)
      // Presents a help message.

      console.log('http-music\nTry man http-music!')

      if (util.index === util.argv.length - 1) {
        shouldPlay = false
      }
    },

    'h': util => util.alias('-help'),
    '?': util => util.alias('-help'),

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

      await openPlaylist(util.nextArg())
    },

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

    '-write-playlist': function(util) {
      // --write-playlist <file>  (alias: --write, -w, --save)
      // Writes the active playlist to a file. This file can later be used
      // with --open <file>; you won't need to stick in all the filtering
      // options again.

      requiresOpenPlaylist()

      const playlistString = JSON.stringify(activePlaylist, null, 2)
      const file = util.nextArg()

      console.log(`Saving playlist to file ${file}...`)

      return writeFile(file, playlistString).then(() => {
        console.log("Saved.")

        // If this is the last option, the user probably doesn't actually
        // want to play the playlist. (We need to check if this is len - 2
        // rather than len - 1, because of the <file> option that comes
        // after --write-playlist.)
        if (util.index === util.argv.length - 2) {
          shouldPlay = false
        }
      })
    },

    '-write': util => util.alias('-write-playlist'),
    'w': util => util.alias('-write-playlist'),
    '-save': util => util.alias('-write-playlist'),

    '-print-playlist': function(util) {
      // --print-playlist  (alias: --log-playlist, --json)
      // Prints out the JSON representation of the active playlist.

      requiresOpenPlaylist()

      console.log(JSON.stringify(activePlaylist, null, 2))

      // As with --write-playlist, the user probably doesn't want to actually
      // play anything if this is the last option.
      if (util.index === util.argv.length - 1) {
        shouldPlay = false
      }
    },

    '-log-playlist': util => util.alias('-print-playlist'),
    '-json': util => util.alias('-print-playlist'),

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

      requiresOpenPlaylist()

      activePlaylist.items = []
    },

    '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 removed an entire parent group, e.g. `-r foo -k foo/baz`.

      requiresOpenPlaylist()

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

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

    '-remove': function(util) {
      // --remove <groupPath>  (alias: -r, -x)
      // Filters the playlist so that the given path is removed.

      requiresOpenPlaylist()

      const pathString = util.nextArg()
      console.log("Ignoring path: " + pathString)
      removeGroupByPathString(activePlaylist, pathString)
    },

    'r': util => util.alias('-remove'),
    'x': util => util.alias('-remove'),

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

      requiresOpenPlaylist()

      console.log(getPlaylistTreeString(activePlaylist))

      // 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.

      requiresOpenPlaylist()

      console.log(getPlaylistTreeString(activePlaylist, 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'),

    '-picker': function(util) {
      // --picker <picker type>  (alias: --selector)
      // Selects the mode that the song to play is picked.
      // See pickers.js.

      pickerType = util.nextArg()
    },

    '-selector': util => util.alias('-picker'),

    '-player': function(util) {
      // --player <player>
      // Sets the shell command by which audio is played.
      // Valid options include 'sox' (or 'play') and 'mpv'. Use whichever is
      // installed on your system.

      playerCommand = util.nextArg()
    }
  }

  await openPlaylist('./playlist.json', true)

  await processArgv(args, optionFunctions)

  if (activePlaylist === null) {
    throw new Error(
      "Cannot play - no open playlist. Try --open <playlist file>?"
    )
  }

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

    console.log(`Using ${playerCommand} player.`)

    const {
      promise: playPromise,
      playController,
      downloadController,
      player
    } = loopPlay(activePlaylist, picker, playerCommand, playOpts)

    // We're looking to gather standard input one keystroke at a time.
    // But that isn't *always* possible, e.g. when piping into the http-music
    // command through the shell.
    if ('setRawMode' in process.stdin) {
      process.stdin.setRawMode(true)
    } else {
      console.warn("User input cannot be gotten!")
      console.warn("If you're piping into http-music, this is normal.")
    }

    process.stdin.on('data', data => {
      const escModifier = Buffer.from('\x1b[')
      const shiftModifier = Buffer.from('1;2')

      const esc = num => Buffer.concat([escModifier, Buffer.from([num])])

      const shiftEsc = num => (
        Buffer.concat([escModifier, shiftModifier, Buffer.from([num])])
      )

      if (Buffer.from([0x20]).equals(data)) {
        player.togglePause()
      }

      if (esc(0x43).equals(data)) {
        player.seekAhead(5)
      }

      if (esc(0x44).equals(data)) {
        player.seekBack(5)
      }

      if (shiftEsc(0x43).equals(data)) {
        player.seekAhead(30)
      }

      if (shiftEsc(0x44).equals(data)) {
        player.seekBack(30)
      }

      if (esc(0x41).equals(data)) {
        player.volUp(10)
      }

      if (esc(0x42).equals(data)) {
        player.volDown(10)
      }

      if (Buffer.from('s').equals(data)) {
        clearConsoleLine()
        console.log(
          "Skipping the track that's currently playing. " +
          "(Press I for track info!)"
        )

        playController.skip()
      }

      if (Buffer.from([0x7f]).equals(data)) {
        clearConsoleLine()
        console.log(
          "Skipping the track that's up next. " +
          "(Press I for track info!)"
        )

        playController.skipUpNext()
      }

      if (
        Buffer.from('i').equals(data) ||
        Buffer.from('t').equals(data)
      ) {
        clearConsoleLine()
        playController.logTrackInfo()
      }

      if (
        Buffer.from('q').equals(data) ||
        Buffer.from([0x03]).equals(data) || // ^C
        Buffer.from([0x04]).equals(data) // ^D
      ) {
        playController.stop().then(() => {
          process.exit(0)
        })
      }
    })

    return playPromise
  } else {
    return activePlaylist
  }
}

module.exports = main

if (require.main === module) {
  main(process.argv.slice(2))
    .catch(err => console.error(err))
}