« get me outta code hell

smart-playlist.js « src - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/smart-playlist.js
blob: 76cd8779c2c37ecd72079eb037122bfd886d566a (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
'use strict'

const fs = require('fs')
const { getCrawlerByName } = require('./crawlers')

const { promisify } = require('util')
const readFile = promisify(fs.readFile)

async function processItem(item) {
  // Object.assign is used so that we keep original properties, e.g. "name"
  // or "apply". (It's also used so we return copies of original objects.)

  if ('source' in item) {
    const [ name, ...args ] = item.source

    const crawlModule = getCrawlerByName(name)

    if (crawlModule === null) {
      console.error(`No crawler by name ${name} - skipped item:`, item)
      return Object.assign({}, item, {failed: true})
    }

    const { crawl } = crawlModule

    return Object.assign({}, item, await crawl(...args))
  } else if ('items' in item) {
    return Object.assign({}, item, {
      items: await Promise.all(item.items.map(processItem))
    })
  } else {
    return Object.assign({}, item)
  }
}

module.exports = processItem

async function main(opts) {
  // TODO: Error when no file is given

  if (opts.length === 0) {
    console.log("Usage: smart-playlist /path/to/playlist")
  } else {
    const playlist = JSON.parse(await readFile(opts[0]))
    console.log(JSON.stringify(await processItem(playlist), null, 2))
  }
}

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