« get me outta code hell

downloaders.js « src - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/downloaders.js
blob: 3f3a427b0c34dd193b5573ad6b09c7bd55fd9688 (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
const fs = require('fs')
const fetch = require('node-fetch')
const promisifyProcess = require('./promisify-process')
const tempy = require('tempy')

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

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

function makeHTTPDownloader() {
  return function(arg, out) {
    return fetch(arg)
      .then(response => response.buffer())
      .then(buffer => writeFile(out, buffer))
  }
}

function makeYouTubeDownloader() {
  return function(arg, out) {
    const tempDir = tempy.directory()

    const opts = [
      '--extract-audio',
      '--audio-format', 'wav',
      '--output', tempDir + '/dl.%(ext)s',
      arg
    ]

    return promisifyProcess(spawn('youtube-dl', opts), false)
      .then(() => rename(tempDir + '/dl.wav', out))
  }
}

function makeLocalDownloader() {
  return function(arg, out) {
    const read = fs.createReadStream(arg)
    const write = fs.createWriteStream(out)

    return new Promise((resolve, reject) => {
      write.on('error', err => reject(err))
      write.on('close', () => resolve())
      read.pipe(write)
    })
  }
}

module.exports = {
  makeHTTPDownloader,
  makeYouTubeDownloader,
  makeLocalDownloader
}