« get me outta code hell

general-util.js - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/general-util.js
blob: 0f5bdd5861b2ef71d8ebc29d8d698ba77807dd61 (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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
const { spawn } = require('child_process')
const { promisify } = require('util')
const fetch = require('node-fetch')
const fs = require('fs')
const npmCommandExists = require('command-exists')
const url = require('url')

const readFile = promisify(fs.readFile)

module.exports.promisifyProcess = function(proc, showLogging = true) {
  // Takes a process (from the child_process module) and returns a promise
  // that resolves when the process exits (or rejects, if the exit code is
  // non-zero).

  return new Promise((resolve, reject) => {
    if (showLogging) {
      proc.stdout.pipe(process.stdout)
      proc.stderr.pipe(process.stderr)
    }

    proc.on('exit', code => {
      if (code === 0) {
        resolve()
      } else {
        reject(code)
      }
    })
  })
}

module.exports.commandExists = async function(command) {
  // When the command-exists module sees that a given command doesn't exist, it
  // throws an error instead of returning false, which is not what we want.

  try {
    return await npmCommandExists(command)
  } catch(err) {
    return false
  }
}

module.exports.killProcess = async function(proc) {
  // Windows is stupid and doesn't like it when we try to kill processes.
  // So instead we use taskkill! https://stackoverflow.com/a/28163919/4633828

  if (await module.exports.commandExists('taskkill')) {
    await module.exports.promisifyProcess(
      spawn('taskkill', ['/pid', proc.pid, '/f', '/t']),
      false
    )
  } else {
    proc.kill()
  }
}

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) {
  let argURL
  try {
    argURL = new url.URL(arg)
  } catch (err) {
    // Definitely not a URL.
  }

  if (argURL) {
    if (argURL.protocol === 'http:' || argURL.protocol === 'https:') {
      return downloadPlaylistFromURL(arg)
    } else if (argURL.protocol === 'file:') {
      return downloadPlaylistFromLocalPath(url.fileURLToPath(argURL))
    }
  } else {
    return downloadPlaylistFromLocalPath(arg)
  }
}

module.exports.shuffleArray = function(array) {
  // Shuffles the items in an array. Returns a new array (does not modify the
  // passed array). Super-interesting post on how this algorithm works:
  // https://bost.ocks.org/mike/shuffle/

  const workingArray = array.slice(0)

  let m = array.length

  while (m) {
    let i = Math.floor(Math.random() * m)
    m--

    // Stupid lol; avoids the need of a temporary variable!
    Object.assign(workingArray, {
      [m]: workingArray[i],
      [i]: workingArray[m]
    })
  }

  return workingArray
}

module.exports.throttlePromise = function(maximumAtOneTime = 10) {
  // Returns a function that takes a callback to create a promise and either
  // runs it now, if there is an available slot, or enqueues it to be run
  // later, if there is not.

  let activeCount = 0
  const queue = []

  const execute = function(callback) {
    activeCount++
    return callback().finally(() => {
      activeCount--

      if (queue.length) {
        return execute(queue.shift())
      }
    })
  }

  const enqueue = function(callback) {
    if (activeCount >= maximumAtOneTime) {
      return new Promise((resolve, reject) => {
        queue.push(function() {
          return callback().then(resolve, reject)
        })
      })
    } else {
      return execute(callback)
    }
  }

  enqueue.queue = queue

  return enqueue
}

module.exports.getTimeStringsFromSec = function(curSecTotal, lenSecTotal) {
  const percentVal = (100 / lenSecTotal) * curSecTotal
  const percentDone = (
    (Math.trunc(percentVal * 100) / 100).toFixed(2) + '%'
  )

  const leftSecTotal = lenSecTotal - curSecTotal
  let leftHour = Math.floor(leftSecTotal / 3600)
  let leftMin = Math.floor((leftSecTotal - leftHour * 3600) / 60)
  let leftSec = Math.floor(leftSecTotal - leftHour * 3600 - leftMin * 60)

  // Yeah, yeah, duplicate math.
  let curHour = Math.floor(curSecTotal / 3600)
  let curMin = Math.floor((curSecTotal - curHour * 3600) / 60)
  let curSec = Math.floor(curSecTotal - curHour * 3600 - curMin * 60)

  // Wee!
  let lenHour = Math.floor(lenSecTotal / 3600)
  let lenMin = Math.floor((lenSecTotal - lenHour * 3600) / 60)
  let lenSec = Math.floor(lenSecTotal - lenHour * 3600 - lenMin * 60)

  const pad = val => val.toString().padStart(2, '0')
  curMin = pad(curMin)
  curSec = pad(curSec)
  lenMin = pad(lenMin)
  lenSec = pad(lenSec)
  leftMin = pad(leftMin)
  leftSec = pad(leftSec)

  // We don't want to display hour counters if the total length is less
  // than an hour.
  let timeDone, timeLeft, duration
  if (parseInt(lenHour) > 0) {
    timeDone = `${curHour}:${curMin}:${curSec}`
    timeLeft = `${leftHour}:${leftMin}:${leftSec}`
    duration = `${lenHour}:${lenMin}:${lenSec}`
  } else {
    timeDone = `${curMin}:${curSec}`
    timeLeft = `${leftMin}:${leftSec}`
    duration = `${lenMin}:${lenSec}`
  }

  return {percentDone, timeDone, timeLeft, duration, curSecTotal, lenSecTotal}
}

module.exports.getTimeStrings = function({curHour, curMin, curSec, lenHour, lenMin, lenSec}) {
  // Multiplication casts to numbers; addition prioritizes strings.
  // Thanks, JavaScript!
  const curSecTotal = (3600 * curHour) + (60 * curMin) + (1 * curSec)
  const lenSecTotal = (3600 * lenHour) + (60 * lenMin) + (1 * lenSec)

  return module.exports.getTimeStringsFromSec(curSecTotal, lenSecTotal)
}

const parseOptions = async function(options, optionDescriptorMap) {
  // This function is sorely lacking in comments, but the basic usage is
  // as such:
  //
  // options is the array of options you want to process;
  // optionDescriptorMap is a mapping of option names to objects that describe
  // the expected value for their corresponding options.
  // Returned is a mapping of any specified option names to their values, or
  // a process.exit(1) and error message if there were any issues.
  //
  // Here are examples of optionDescriptorMap to cover all the things you can
  // do with it:
  //
  // optionDescriptorMap: {
  //   'telnet-server': {type: 'flag'},
  //   't': {alias: 'telnet-server'}
  // }
  //
  // options: ['t'] -> result: {'telnet-server': true}
  //
  // optionDescriptorMap: {
  //   'directory': {
  //     type: 'value',
  //     validate(name) {
  //       // const whitelistedDirectories = ['apple', 'banana']
  //       if (whitelistedDirectories.includes(name)) {
  //         return true
  //       } else {
  //         return 'a whitelisted directory'
  //       }
  //     }
  //   },
  //   'files': {type: 'series'}
  // }
  //
  // ['--directory', 'apple'] -> {'directory': 'apple'}
  // ['--directory', 'artichoke'] -> (error)
  // ['--files', 'a', 'b', 'c', ';'] -> {'files': ['a', 'b', 'c']}
  //
  // TODO: Be able to validate the values in a series option.

  const handleDashless = optionDescriptorMap[parseOptions.handleDashless]
  const result = {}
  for (let i = 0; i < options.length; i++) {
    const option = options[i]
    if (option.startsWith('--')) {
      // --x can be a flag or expect a value or series of values
      let name = option.slice(2).split('=')[0] // '--x'.split('=') = ['--x']
      let descriptor = optionDescriptorMap[name]
      if (!descriptor) {
        console.error(`Unknown option name: ${name}`)
        process.exit(1)
      }
      if (descriptor.alias) {
        name = descriptor.alias
        descriptor = optionDescriptorMap[name]
      }
      if (descriptor.type === 'flag') {
        result[name] = true
      } else if (descriptor.type === 'value') {
        let value = option.slice(2).split('=')[1]
        if (!value) {
          value = options[++i]
          if (!value || value.startsWith('-')) {
            value = null
          }
        }
        if (!value) {
          console.error(`Expected a value for --${name}`)
          process.exit(1)
        }
        result[name] = value
      } else if (descriptor.type === 'series') {
        if (!options.slice(i).includes(';')) {
          console.error(`Expected a series of values concluding with ; (\\;) for --${name}`)
          process.exit(1)
        }
        const endIndex = i + options.slice(i).indexOf(';')
        result[name] = options.slice(i + 1, endIndex)
        i = endIndex
      }
      if (descriptor.validate) {
        const validation = await descriptor.validate(result[name])
        if (validation !== true) {
          console.error(`Expected ${validation} for --${name}`)
          process.exit(1)
        }
      }
    } else if (option.startsWith('-')) {
      // mtui doesn't use any -x=y or -x y format optionuments
      // -x will always just be a flag
      let name = option.slice(1)
      let descriptor = optionDescriptorMap[name]
      if (!descriptor) {
        console.error(`Unknown option name: ${name}`)
        process.exit(1)
      }
      if (descriptor.alias) {
        name = descriptor.alias
        descriptor = optionDescriptorMap[name]
      }
      if (descriptor.type === 'flag') {
        result[name] = true
      } else {
        console.error(`Use --${name} (value) to specify ${name}`)
        process.exit(1)
      }
    } else if (handleDashless) {
      handleDashless(option)
    }
  }
  return result
}

parseOptions.handleDashless = Symbol()

module.exports.parseOptions = parseOptions

module.exports.silenceEvents = async function(emitter, eventsToSilence, callback) {
  const oldEmit = emitter.emit

  emitter.emit = function(event, ...data) {
    if (!eventsToSilence.includes(event)) {
      oldEmit.apply(emitter, [event, ...data])
    }
  }

  await callback()

  emitter.emit = oldEmit
}