89 lines
2.3 KiB
JavaScript
89 lines
2.3 KiB
JavaScript
const { spawnSync } = require('child_process')
|
|
const fs = require('fs')
|
|
|
|
const getPlaylist = () => {
|
|
const { stderr, stdout } = spawnSync('mpc', ['playlist'])
|
|
return { error: stderr.toString(), playlist: stdout.toString() }
|
|
}
|
|
|
|
const getCurrentTrack = () => {
|
|
const { stderr, stdout } = spawnSync('mpc', ['current'])
|
|
return { error: stderr.toString(), track: stdout.toString() }
|
|
}
|
|
|
|
const skipTrack = () => {
|
|
const { track } = getCurrentTrack()
|
|
const { stderr } = spawnSync('mpc', ['next'])
|
|
return { error: stderr.toString(), skip: track }
|
|
}
|
|
|
|
const insertTrack = spotifyURI => {
|
|
console.log('inserting track:', JSON.stringify(spotifyURI))
|
|
const { stderr, stdout } = spawnSync('mpc', ['insert', spotifyURI])
|
|
console.log(stderr.toString(), stdout.toString())
|
|
return { error: stderr.toString(), insert: stdout.toString() }
|
|
}
|
|
|
|
const insertTrackAsync = spotifyURI => {
|
|
console.log('inserting track:', spotifyURI)
|
|
const promise = new Promise((resolve, reject) => {
|
|
const { stdout, error } = spawnSync('mpc', ['insert', spotifyURI])
|
|
if (error) reject(error.message)
|
|
resolve({ track: stdout.toString() })
|
|
})
|
|
return promise
|
|
}
|
|
|
|
const reset = event => {
|
|
clearAllPlaylists(event)
|
|
addAllPlaylists(event)
|
|
}
|
|
|
|
const clearAllPlaylists = event => {
|
|
const { error } = spawnSync('mpc', ['clear'])
|
|
if (error) return handleError(error, event)
|
|
}
|
|
|
|
const addAllPlaylists = async event => {
|
|
try {
|
|
const files = fs.readdirSync('./playlists')
|
|
const tracks = readPlaylists(files)
|
|
await Promise.all(
|
|
tracks.map(t => insertTrackAsync(t.split(' # ')[0]))
|
|
).then(() => {
|
|
shuffleAllPlaylists()
|
|
play()
|
|
})
|
|
} catch (e) {
|
|
return handleError(e, event)
|
|
}
|
|
}
|
|
|
|
const readPlaylists = files =>
|
|
files
|
|
.map(f => fs.readFileSync('./playlists/' + f, 'utf-8').split('\n'))
|
|
.reduce((a, b) => a.concat(b))
|
|
|
|
const handleError = (err, event) => {
|
|
console.log(err)
|
|
return event.reply('Something went wrong.')
|
|
}
|
|
|
|
const shuffleAllPlaylists = event => {
|
|
const { error } = spawnSync('mpc', ['shuffle'])
|
|
if (error) return handleError(error, event)
|
|
}
|
|
|
|
const play = event => {
|
|
const { error } = spawnSync('mpc', ['play'])
|
|
if (error) return handleError(error, event)
|
|
}
|
|
|
|
module.exports = {
|
|
getPlaylist,
|
|
getCurrentTrack,
|
|
skipTrack,
|
|
insertTrack,
|
|
reset,
|
|
}
|