« get me outta code hell

general-util.js « src - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/general-util.js
blob: 825dd90541ec163b0be7a7055e9f86cd51484115 (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
const { promisify } = require('util')
const fs = require('fs')
const fetch = require('node-fetch')

const readFile = promisify(fs.readFile)

module.exports.showTrackProcessStatus = function(
  total, doneCount, noLineBreak = false
) {
  // Log a status line which tells how many tracks are processed and what
  // percent is completed. (Uses non-specific language: it doesn't say
  // "how many tracks downloaded" or "how many tracks processed", but
  // rather, "how many tracks completed".) Pass noLineBreak = true to skip
  // the \n character (you'll probably also want to log \r after).

  const percent = Math.trunc(doneCount / total * 10000) / 100
  process.stdout.write(
    `\x1b[1m${percent}% completed ` +
    `(${doneCount}/${total} tracks)\x1b[0m` +
    (noLineBreak ? '' : '\n')
  )
}

function downloadPlaylistFromURL(url) {
  return fetch(url).then(res => res.text())
}

function downloadPlaylistFromLocalPath(path) {
  return readFile(path).then(buf => buf.toString())
}

module.exports.downloadPlaylistFromOptionValue = function(arg) {
  // TODO: Verify things!
  if (arg.startsWith('http://') || arg.startsWith('https://')) {
    return downloadPlaylistFromURL(arg)
  } else {
    return downloadPlaylistFromLocalPath(arg)
  }
}