general-util.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 = null, fraction = false) {
  124. const pad = val => val.toString().padStart(2, '0')
  125. const padFrac = val => Math.floor(val * 1000).toString().padEnd(3, '0')
  126. // We don't want to display hour counters if the total length is less
  127. // than an hour.
  128. const displayAsHours = Math.max(curSecTotal, lenSecTotal ?? 0) >= 3600
  129. const strings = {curSecTotal, lenSecTotal}
  130. let curHour = Math.floor(curSecTotal / 3600)
  131. let curMin = Math.floor((curSecTotal - curHour * 3600) / 60)
  132. let curSec = Math.floor(curSecTotal - curHour * 3600 - curMin * 60)
  133. let curFrac = curSecTotal % 1
  134. curMin = pad(curMin)
  135. curSec = pad(curSec)
  136. curFrac = padFrac(curFrac)
  137. if (displayAsHours) {
  138. strings.timeDone = `${curHour}:${curMin}:${curSec}`
  139. } else {
  140. strings.timeDone = `${curMin}:${curSec}`
  141. }
  142. if (fraction) {
  143. strings.timeDone += '.' + curFrac
  144. }
  145. if (typeof lenSecTotal === 'number') {
  146. const percentVal = (100 / lenSecTotal) * curSecTotal
  147. strings.percentDone = (Math.trunc(percentVal * 100) / 100).toFixed(2) + '%'
  148. // Yeah, yeah, duplicate math.
  149. const leftSecTotal = lenSecTotal - curSecTotal
  150. let leftHour = Math.floor(leftSecTotal / 3600)
  151. let leftMin = Math.floor((leftSecTotal - leftHour * 3600) / 60)
  152. let leftSec = Math.floor(leftSecTotal - leftHour * 3600 - leftMin * 60)
  153. let leftFrac = leftSecTotal % 1
  154. // Wee!
  155. let lenHour = Math.floor(lenSecTotal / 3600)
  156. let lenMin = Math.floor((lenSecTotal - lenHour * 3600) / 60)
  157. let lenSec = Math.floor(lenSecTotal - lenHour * 3600 - lenMin * 60)
  158. let lenFrac = lenSecTotal % 1
  159. lenMin = pad(lenMin)
  160. lenSec = pad(lenSec)
  161. lenFrac = padFrac(lenFrac)
  162. leftMin = pad(leftMin)
  163. leftSec = pad(leftSec)
  164. leftFrac = padFrac(leftFrac)
  165. if (typeof lenSecTotal === 'number') {
  166. if (displayAsHours) {
  167. strings.timeLeft = `${leftHour}:${leftMin}:${leftSec}`
  168. strings.duration = `${lenHour}:${lenMin}:${lenSec}`
  169. } else {
  170. strings.timeLeft = `${leftMin}:${leftSec}`
  171. strings.duration = `${lenMin}:${lenSec}`
  172. }
  173. if (fraction) {
  174. strings.timeLeft += '.' + leftFrac
  175. strings.duration += '.' + lenFrac
  176. }
  177. }
  178. }
  179. return strings
  180. }
  181. export function getTimeStrings({curHour, curMin, curSec, lenHour, lenMin, lenSec}) {
  182. // Multiplication casts to numbers; addition prioritizes strings.
  183. // Thanks, JavaScript!
  184. const curSecTotal = (3600 * curHour) + (60 * curMin) + (1 * curSec)
  185. const lenSecTotal = (3600 * lenHour) + (60 * lenMin) + (1 * lenSec)
  186. return getTimeStringsFromSec(curSecTotal, lenSecTotal)
  187. }
  188. export async function parseOptions(options, optionDescriptorMap) {
  189. // This function is sorely lacking in comments, but the basic usage is
  190. // as such:
  191. //
  192. // options is the array of options you want to process;
  193. // optionDescriptorMap is a mapping of option names to objects that describe
  194. // the expected value for their corresponding options.
  195. // Returned is a mapping of any specified option names to their values, or
  196. // a process.exit(1) and error message if there were any issues.
  197. //
  198. // Here are examples of optionDescriptorMap to cover all the things you can
  199. // do with it:
  200. //
  201. // optionDescriptorMap: {
  202. // 'telnet-server': {type: 'flag'},
  203. // 't': {alias: 'telnet-server'}
  204. // }
  205. //
  206. // options: ['t'] -> result: {'telnet-server': true}
  207. //
  208. // optionDescriptorMap: {
  209. // 'directory': {
  210. // type: 'value',
  211. // validate(name) {
  212. // // const whitelistedDirectories = ['apple', 'banana']
  213. // if (whitelistedDirectories.includes(name)) {
  214. // return true
  215. // } else {
  216. // return 'a whitelisted directory'
  217. // }
  218. // }
  219. // },
  220. // 'files': {type: 'series'}
  221. // }
  222. //
  223. // ['--directory', 'apple'] -> {'directory': 'apple'}
  224. // ['--directory', 'artichoke'] -> (error)
  225. // ['--files', 'a', 'b', 'c', ';'] -> {'files': ['a', 'b', 'c']}
  226. //
  227. // TODO: Be able to validate the values in a series option.
  228. const handleDashless = optionDescriptorMap[parseOptions.handleDashless]
  229. const result = {}
  230. for (let i = 0; i < options.length; i++) {
  231. const option = options[i]
  232. if (option.startsWith('--')) {
  233. // --x can be a flag or expect a value or series of values
  234. let name = option.slice(2).split('=')[0] // '--x'.split('=') = ['--x']
  235. let descriptor = optionDescriptorMap[name]
  236. if (!descriptor) {
  237. console.error(`Unknown option name: ${name}`)
  238. process.exit(1)
  239. }
  240. if (descriptor.alias) {
  241. name = descriptor.alias
  242. descriptor = optionDescriptorMap[name]
  243. }
  244. if (descriptor.type === 'flag') {
  245. result[name] = true
  246. } else if (descriptor.type === 'value') {
  247. let value = option.slice(2).split('=')[1]
  248. if (!value) {
  249. value = options[++i]
  250. if (!value || value.startsWith('-')) {
  251. value = null
  252. }
  253. }
  254. if (!value) {
  255. console.error(`Expected a value for --${name}`)
  256. process.exit(1)
  257. }
  258. result[name] = value
  259. } else if (descriptor.type === 'series') {
  260. if (!options.slice(i).includes(';')) {
  261. console.error(`Expected a series of values concluding with ; (\\;) for --${name}`)
  262. process.exit(1)
  263. }
  264. const endIndex = i + options.slice(i).indexOf(';')
  265. result[name] = options.slice(i + 1, endIndex)
  266. i = endIndex
  267. }
  268. if (descriptor.validate) {
  269. const validation = await descriptor.validate(result[name])
  270. if (validation !== true) {
  271. console.error(`Expected ${validation} for --${name}`)
  272. process.exit(1)
  273. }
  274. }
  275. } else if (option.startsWith('-')) {
  276. // mtui doesn't use any -x=y or -x y format optionuments
  277. // -x will always just be a flag
  278. let name = option.slice(1)
  279. let descriptor = optionDescriptorMap[name]
  280. if (!descriptor) {
  281. console.error(`Unknown option name: ${name}`)
  282. process.exit(1)
  283. }
  284. if (descriptor.alias) {
  285. name = descriptor.alias
  286. descriptor = optionDescriptorMap[name]
  287. }
  288. if (descriptor.type === 'flag') {
  289. result[name] = true
  290. } else {
  291. console.error(`Use --${name} (value) to specify ${name}`)
  292. process.exit(1)
  293. }
  294. } else if (handleDashless) {
  295. handleDashless(option)
  296. }
  297. }
  298. return result
  299. }
  300. parseOptions.handleDashless = Symbol()
  301. export async function silenceEvents(emitter, eventsToSilence, callback) {
  302. const oldEmit = emitter.emit
  303. emitter.emit = function(event, ...data) {
  304. if (!eventsToSilence.includes(event)) {
  305. oldEmit.apply(emitter, [event, ...data])
  306. }
  307. }
  308. await callback()
  309. emitter.emit = oldEmit
  310. }
  311. // Kindly stolen from ESDiscuss:
  312. // https://esdiscuss.org/topic/proposal-add-an-option-to-omit-prototype-of-objects-created-by-json-parse#content-1
  313. export function parseWithoutPrototype(string) {
  314. return JSON.parse(string, function(k, v) {
  315. if (v && typeof v === 'object' && !Array.isArray(v)) {
  316. return Object.assign(Object.create(null), v)
  317. }
  318. return v
  319. })
  320. }