general-util.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import {spawn} from 'node:child_process'
  2. import {readFile} from 'node:fs/promises'
  3. import {fileURLToPath, URL} from 'node:url'
  4. import npmCommandExists from 'command-exists'
  5. import fetch from 'node-fetch'
  6. export function promisifyProcess(proc, showLogging = true) {
  7. // Takes a process (from the child_process module) and returns a promise
  8. // that resolves when the process exits (or rejects, if the exit code is
  9. // non-zero).
  10. return new Promise((resolve, reject) => {
  11. if (showLogging) {
  12. proc.stdout.pipe(process.stdout)
  13. proc.stderr.pipe(process.stderr)
  14. }
  15. proc.on('exit', code => {
  16. if (code === 0) {
  17. resolve()
  18. } else {
  19. reject(code)
  20. }
  21. })
  22. })
  23. }
  24. export async function commandExists(command) {
  25. // When the command-exists module sees that a given command doesn't exist, it
  26. // throws an error instead of returning false, which is not what we want.
  27. try {
  28. return await npmCommandExists(command)
  29. } catch(err) {
  30. return false
  31. }
  32. }
  33. export async function killProcess(proc) {
  34. // Windows is stupid and doesn't like it when we try to kill processes.
  35. // So instead we use taskkill! https://stackoverflow.com/a/28163919/4633828
  36. if (await commandExists('taskkill')) {
  37. await promisifyProcess(
  38. spawn('taskkill', ['/pid', proc.pid, '/f', '/t']),
  39. false
  40. )
  41. } else {
  42. proc.kill()
  43. }
  44. }
  45. export function downloadPlaylistFromURL(url) {
  46. return fetch(url).then(res => res.text())
  47. }
  48. export function downloadPlaylistFromLocalPath(path) {
  49. return readFile(path).then(buf => buf.toString())
  50. }
  51. export function downloadPlaylistFromOptionValue(arg) {
  52. let argURL
  53. try {
  54. argURL = new URL(arg)
  55. } catch (err) {
  56. // Definitely not a URL.
  57. }
  58. if (argURL) {
  59. if (argURL.protocol === 'http:' || argURL.protocol === 'https:') {
  60. return downloadPlaylistFromURL(arg)
  61. } else if (argURL.protocol === 'file:') {
  62. return downloadPlaylistFromLocalPath(fileURLToPath(argURL))
  63. }
  64. } else {
  65. return downloadPlaylistFromLocalPath(arg)
  66. }
  67. }
  68. export function shuffleArray(array) {
  69. // Shuffles the items in an array. Returns a new array (does not modify the
  70. // passed array). Super-interesting post on how this algorithm works:
  71. // https://bost.ocks.org/mike/shuffle/
  72. const workingArray = array.slice(0)
  73. let m = array.length
  74. while (m) {
  75. let i = Math.floor(Math.random() * m)
  76. m--
  77. // Stupid lol; avoids the need of a temporary variable!
  78. Object.assign(workingArray, {
  79. [m]: workingArray[i],
  80. [i]: workingArray[m]
  81. })
  82. }
  83. return workingArray
  84. }
  85. export function throttlePromise(maximumAtOneTime = 10) {
  86. // Returns a function that takes a callback to create a promise and either
  87. // runs it now, if there is an available slot, or enqueues it to be run
  88. // later, if there is not.
  89. let activeCount = 0
  90. const queue = []
  91. const execute = function(callback) {
  92. activeCount++
  93. return callback().finally(() => {
  94. activeCount--
  95. if (queue.length) {
  96. return execute(queue.shift())
  97. }
  98. })
  99. }
  100. const enqueue = function(callback) {
  101. if (activeCount >= maximumAtOneTime) {
  102. return new Promise((resolve, reject) => {
  103. queue.push(function() {
  104. return callback().then(resolve, reject)
  105. })
  106. })
  107. } else {
  108. return execute(callback)
  109. }
  110. }
  111. enqueue.queue = queue
  112. return enqueue
  113. }
  114. export function getSecFromTimestamp(timestamp) {
  115. const parts = timestamp.split(':').map(n => parseInt(n))
  116. switch (parts.length) {
  117. case 3: return parts[0] * 3600 + parts[1] * 60 + parts[2]
  118. case 2: return parts[0] * 60 + parts[1]
  119. case 1: return parts[0]
  120. default: return 0
  121. }
  122. }
  123. export function getTimeStringsFromSec(curSecTotal, lenSecTotal, fraction = false) {
  124. const percentVal = (100 / lenSecTotal) * curSecTotal
  125. const percentDone = (
  126. (Math.trunc(percentVal * 100) / 100).toFixed(2) + '%'
  127. )
  128. const leftSecTotal = lenSecTotal - curSecTotal
  129. let leftHour = Math.floor(leftSecTotal / 3600)
  130. let leftMin = Math.floor((leftSecTotal - leftHour * 3600) / 60)
  131. let leftSec = Math.floor(leftSecTotal - leftHour * 3600 - leftMin * 60)
  132. let leftFrac = lenSecTotal % 1
  133. // Yeah, yeah, duplicate math.
  134. let curHour = Math.floor(curSecTotal / 3600)
  135. let curMin = Math.floor((curSecTotal - curHour * 3600) / 60)
  136. let curSec = Math.floor(curSecTotal - curHour * 3600 - curMin * 60)
  137. let curFrac = curSecTotal % 1
  138. // Wee!
  139. let lenHour = Math.floor(lenSecTotal / 3600)
  140. let lenMin = Math.floor((lenSecTotal - lenHour * 3600) / 60)
  141. let lenSec = Math.floor(lenSecTotal - lenHour * 3600 - lenMin * 60)
  142. let lenFrac = lenSecTotal % 1
  143. const pad = val => val.toString().padStart(2, '0')
  144. const padFrac = val => Math.floor(val * 1000).toString().padEnd(3, '0')
  145. curMin = pad(curMin)
  146. curSec = pad(curSec)
  147. lenMin = pad(lenMin)
  148. lenSec = pad(lenSec)
  149. leftMin = pad(leftMin)
  150. leftSec = pad(leftSec)
  151. curFrac = padFrac(curFrac)
  152. lenFrac = padFrac(lenFrac)
  153. leftFrac = padFrac(leftFrac)
  154. // We don't want to display hour counters if the total length is less
  155. // than an hour.
  156. let timeDone, timeLeft, duration
  157. if (parseInt(lenHour) > 0 || parseInt(curHour) > 0) {
  158. timeDone = `${curHour}:${curMin}:${curSec}`
  159. timeLeft = `${leftHour}:${leftMin}:${leftSec}`
  160. duration = `${lenHour}:${lenMin}:${lenSec}`
  161. } else {
  162. timeDone = `${curMin}:${curSec}`
  163. timeLeft = `${leftMin}:${leftSec}`
  164. duration = `${lenMin}:${lenSec}`
  165. }
  166. if (fraction) {
  167. timeDone += '.' + curFrac
  168. timeLeft += '.' + leftFrac
  169. duration += '.' + lenFrac
  170. }
  171. return {percentDone, timeDone, timeLeft, duration, curSecTotal, lenSecTotal}
  172. }
  173. export function getTimeStrings({curHour, curMin, curSec, lenHour, lenMin, lenSec}) {
  174. // Multiplication casts to numbers; addition prioritizes strings.
  175. // Thanks, JavaScript!
  176. const curSecTotal = (3600 * curHour) + (60 * curMin) + (1 * curSec)
  177. const lenSecTotal = (3600 * lenHour) + (60 * lenMin) + (1 * lenSec)
  178. return getTimeStringsFromSec(curSecTotal, lenSecTotal)
  179. }
  180. export async function parseOptions(options, optionDescriptorMap) {
  181. // This function is sorely lacking in comments, but the basic usage is
  182. // as such:
  183. //
  184. // options is the array of options you want to process;
  185. // optionDescriptorMap is a mapping of option names to objects that describe
  186. // the expected value for their corresponding options.
  187. // Returned is a mapping of any specified option names to their values, or
  188. // a process.exit(1) and error message if there were any issues.
  189. //
  190. // Here are examples of optionDescriptorMap to cover all the things you can
  191. // do with it:
  192. //
  193. // optionDescriptorMap: {
  194. // 'telnet-server': {type: 'flag'},
  195. // 't': {alias: 'telnet-server'}
  196. // }
  197. //
  198. // options: ['t'] -> result: {'telnet-server': true}
  199. //
  200. // optionDescriptorMap: {
  201. // 'directory': {
  202. // type: 'value',
  203. // validate(name) {
  204. // // const whitelistedDirectories = ['apple', 'banana']
  205. // if (whitelistedDirectories.includes(name)) {
  206. // return true
  207. // } else {
  208. // return 'a whitelisted directory'
  209. // }
  210. // }
  211. // },
  212. // 'files': {type: 'series'}
  213. // }
  214. //
  215. // ['--directory', 'apple'] -> {'directory': 'apple'}
  216. // ['--directory', 'artichoke'] -> (error)
  217. // ['--files', 'a', 'b', 'c', ';'] -> {'files': ['a', 'b', 'c']}
  218. //
  219. // TODO: Be able to validate the values in a series option.
  220. const handleDashless = optionDescriptorMap[parseOptions.handleDashless]
  221. const result = {}
  222. for (let i = 0; i < options.length; i++) {
  223. const option = options[i]
  224. if (option.startsWith('--')) {
  225. // --x can be a flag or expect a value or series of values
  226. let name = option.slice(2).split('=')[0] // '--x'.split('=') = ['--x']
  227. let descriptor = optionDescriptorMap[name]
  228. if (!descriptor) {
  229. console.error(`Unknown option name: ${name}`)
  230. process.exit(1)
  231. }
  232. if (descriptor.alias) {
  233. name = descriptor.alias
  234. descriptor = optionDescriptorMap[name]
  235. }
  236. if (descriptor.type === 'flag') {
  237. result[name] = true
  238. } else if (descriptor.type === 'value') {
  239. let value = option.slice(2).split('=')[1]
  240. if (!value) {
  241. value = options[++i]
  242. if (!value || value.startsWith('-')) {
  243. value = null
  244. }
  245. }
  246. if (!value) {
  247. console.error(`Expected a value for --${name}`)
  248. process.exit(1)
  249. }
  250. result[name] = value
  251. } else if (descriptor.type === 'series') {
  252. if (!options.slice(i).includes(';')) {
  253. console.error(`Expected a series of values concluding with ; (\\;) for --${name}`)
  254. process.exit(1)
  255. }
  256. const endIndex = i + options.slice(i).indexOf(';')
  257. result[name] = options.slice(i + 1, endIndex)
  258. i = endIndex
  259. }
  260. if (descriptor.validate) {
  261. const validation = await descriptor.validate(result[name])
  262. if (validation !== true) {
  263. console.error(`Expected ${validation} for --${name}`)
  264. process.exit(1)
  265. }
  266. }
  267. } else if (option.startsWith('-')) {
  268. // mtui doesn't use any -x=y or -x y format optionuments
  269. // -x will always just be a flag
  270. let name = option.slice(1)
  271. let descriptor = optionDescriptorMap[name]
  272. if (!descriptor) {
  273. console.error(`Unknown option name: ${name}`)
  274. process.exit(1)
  275. }
  276. if (descriptor.alias) {
  277. name = descriptor.alias
  278. descriptor = optionDescriptorMap[name]
  279. }
  280. if (descriptor.type === 'flag') {
  281. result[name] = true
  282. } else {
  283. console.error(`Use --${name} (value) to specify ${name}`)
  284. process.exit(1)
  285. }
  286. } else if (handleDashless) {
  287. handleDashless(option)
  288. }
  289. }
  290. return result
  291. }
  292. parseOptions.handleDashless = Symbol()