« get me outta code hell

http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/downloaders.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/downloaders.js')
-rw-r--r--src/downloaders.js36
1 files changed, 36 insertions, 0 deletions
diff --git a/src/downloaders.js b/src/downloaders.js
new file mode 100644
index 0000000..527f67d
--- /dev/null
+++ b/src/downloaders.js
@@ -0,0 +1,36 @@
+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))
+  }
+}
+
+module.exports = {makeHTTPDownloader, makeYouTubeDownloader}