« get me outta code hell

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

'use strict'

const fs = require('fs')
const path = require('path')
const sanitize = require('sanitize-filename')
const promisifyProcess = require('./promisify-process')

const {
  flattenGrouplike, updatePlaylistFormat, getItemPath
} = require('./playlist-utils')

const { getDownloaderFor, makePowerfulDownloader } = require('./downloaders')
const { promisify } = require('util')
const { spawn } = require('child_process')

const mkdirp = promisify(require('mkdirp'))

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

async function downloadCrawl(playlist, topOut = './out/') {
  const flat = flattenGrouplike(playlist)
  let doneCount = 0

  const status = function() {
    const total = flat.items.length
    const percent = Math.trunc(doneCount / total * 10000) / 100
    console.log(
      `\x1b[1mDownload crawler - ${percent}% completed ` +
      `(${doneCount}/${total} tracks)\x1b[0m`)
  }

  for (let item of flat.items) {
    const parentGroups = getItemPath(item).slice(0, -1)

    const dir = parentGroups.reduce((a, b) => {
      return a + '/' + sanitize(b.name)
    }, topOut) + '/'

    await mkdirp(dir)

    const base = path.basename(item.name, path.extname(item.name))
    const targetFile = dir + sanitize(base) + '.mp3'

    // If we've already downloaded a file at some point in previous time,
    // there's no need to download it again!
    //
    // Since we can't guarantee the extension name of the file, we only
    // compare bases.
    //
    // TODO: This probably doesn't work well with things like the YouTube
    // downloader.
    const items = await readdir(dir)
    const match = items.find(item => {
      const itemBase = sanitize(path.basename(item, path.extname(item)))
      return itemBase === base
    })

    if (match) {
      console.log(`\x1b[32;2mAlready downloaded: ${targetFile}\x1b[0m`)
      doneCount++
      status()
      continue
    }

    console.log(
      `\x1b[2mDownloading: ${item.name} - ${item.downloaderArg}` +
      ` => ${targetFile}\x1b[0m`
    )

    // Woo-hoo, using block labels for their intended purpose! (Maybe?)
    downloadProcess: {
      const downloader = makePowerfulDownloader(
        getDownloaderFor(item.downloaderArg)
      )

      const outputtedFile = await downloader(item.downloaderArg)

      // If the return of the downloader is false, then the download
      // failed.
      if (outputtedFile === false) {
        console.error(
          `\x1b[33;1mDownload failed (item skipped): ${item.name}\x1b[0m`
        )

        break downloadProcess
      }

      try {
        await promisifyProcess(spawn('ffmpeg', [
          '-i', outputtedFile,

          // A bug (in ffmpeg or macOS; not this) makes it necessary to have
          // these options on macOS, otherwise the outputted file length is
          // wrong.
          '-write_xing', '0',

          targetFile
        ]), false)
      } catch(err) {
        console.error(
          `\x1b[33;1mFFmpeg failed (item skipped): ${item.name}\x1b[0m`
        )

        break downloadProcess
      }

      console.log('Added:', item.name)
    }

    doneCount++

    status()
  }
}

async function main(args) {
  // TODO: Implement command line stuff here

  if (args.length === 0) {
    console.error('Usage: download-playlist <playlistFile> [opts]')
    return
  }

  const playlist = updatePlaylistFormat(JSON.parse(await readFile(args[0])))

  await downloadCrawl(playlist)

  console.log(
    'Done - downloaded to out/. (Use crawl-local out/ to create a playlist.)'
  )
}

module.exports = main

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