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
|
const { spawn } = require('child_process')
const { promisify } = require('util')
const fetch = require('node-fetch')
const fs = require('fs')
const npmCommandExists = require('command-exists')
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) {
// TODO: Verify things!
if (arg.startsWith('http://') || arg.startsWith('https://')) {
return downloadPlaylistFromURL(arg)
} 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
}
|