« 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: 8fa830c4cbf2cad2802ca049a8fbf83b38a1e94d (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
'use strict'

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

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

const writeFile = promisify(fs.writeFile)

function makeHTTPDownloader() {
  return function(arg) {
    const dir = tempy.directory()
    const out = dir + '/' + sanitize(decodeURIComponent(path.basename(arg)))

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

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

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

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

function makeLocalDownloader() {
  return function(arg) {
    // Since we're grabbing the file from the local file system, there's no
    // need to download or copy it!
    return arg
  }
}

function makePowerfulDownloader(downloader, maxAttempts = 5) {
  // This should totally be named better..

  return async function recursive(arg, attempts = 0) {
    try {
      return await downloader(arg)
    } catch(err) {
      if (attempts < maxAttempts) {
        console.warn('Failed - attempting again:', arg)
        return await recursive(arg, attempts + 1)
      } else {
        throw err
      }
    }
  }
}

module.exports = {
  makeHTTPDownloader,
  makeYouTubeDownloader,
  makeLocalDownloader,
  makePowerfulDownloader,

  getDownloader: downloaderType => {
    if (downloaderType === 'http') {
      return makeHTTPDownloader()
    } else if (downloaderType === 'youtube') {
      return makeYouTubeDownloader()
    } else if (downloaderType === 'local') {
      return makeLocalDownloader()
    } else {
      return null
    }
  }
}