« 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: 852cb64500f4b0a956a5eade43d020fba1a3b245 (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
#!/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 { showTrackProcessStatus } = require('./general-util')
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 showStatus = () => {
    showTrackProcessStatus(flat.items.length, doneCount)
  }

  // First off, we go through all tracks and see which are already downloaded.
  // We store the ones that *aren't* downloaded in an 'itemsToDownload' array,
  // which we use later.
  const itemsToDownload = []

  const targetFileSymbol = Symbol('Target file')

  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) + '/'

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

    // We'll be using the target file later when we download all tracks, so
    // we save that right on the playlist item.
    item[targetFileSymbol] = targetFile

    await mkdirp(dir)

    // 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++
      showStatus()
    } else {
      itemsToDownload.push(item)
    }
  }

  // Now that we've decided on which items we need to download, we go through
  // and download all of them.
  for (let item of itemsToDownload) {
    const targetFile = item[targetFileSymbol]

    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 {
        console.log(targetFile)

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

    doneCount++

    showStatus()
  }
}

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))
}