fix: treeshaking

This commit is contained in:
Mateusz Pstrucha committed 2021-11-30 17:53:21 +01:00
1 parent 5e402024b5
commit 00fc789576
10 files changed
+127 -131

No files matched your search

+16
View File
@@ -3,3 +3,19 @@ import dotenv from 'dotenv'
const config = dotenv.config()
export default config
const defaultVolume = parseInt(process.env.VOLUME_DEFAULT ?? 100),
offset = Number(process.env.OFFSET ?? 0),
verbose = Number(process.env.VERBOSE ?? 0),
limit = Number(process.env.LIMIT ?? 40),
{ DOMAIN, SECRET, GENIUS_KEY } = process.env
export {
defaultVolume,
offset,
verbose,
limit,
DOMAIN as domain,
SECRET as secret,
GENIUS_KEY as geniusKey,
}
+2
View File
@@ -0,0 +1,2 @@
find cache/* -mtime +7
find cache/* -mtime +7 -exec rm {} \;
+6 -9
View File
@@ -1,13 +1,10 @@
import env from '../../env.js'
import { domain, secret, verbose } from '../../env.js'
import chalk from 'chalk'
import got from 'got'
import spotifyToYt from 'spotify-to-yt'
import { logAction, logValue } from './log.js'
const { DOMAIN, SECRET } = process.env,
headers = { authorization: 'Bearer ' + SECRET },
verbose = Number(process.env.VERBOSE)
const headers = { authorization: 'Bearer ' + secret }
function updateStatus(tid, progress, duration, paused) {
return new Promise((resolve, reject) => {
@@ -45,10 +42,10 @@ function updateNext(tid) {
}
function getTop(mode = 'once') {
logAction(`Fetching tids`, mode)
logAction(`Fetching tids`, mode, domain)
return got
.get(`https://${DOMAIN}/api/player/get/top?mode=${mode}`, {
.get(`https://${domain}/api/player/get/top?mode=${mode}`, {
headers,
})
.json()
@@ -59,7 +56,7 @@ function getTop(mode = 'once') {
}
function getTrack(tid) {
return got.get(`https://${DOMAIN}/api/track/${tid}`).json()
return got.get(`https://${domain}/api/track/${tid}`).json()
}
export { updateStatus, updateNext, getTop, getTrack }
+2 -2
View File
@@ -4,8 +4,8 @@ function logValue(label, value) {
console.info(label + ':', chalk.yellow(value))
}
function logAction(label, value = '') {
console.info(chalk.bold(label), chalk.yellow(value))
function logAction(label, ...value) {
console.info(chalk.bold(label), chalk.yellow(value.join(' ')))
}
function logError(label, value) {
+5 -33
View File
@@ -1,11 +1,9 @@
import env from '../../env.js'
import { geniusKey } from '../../env.js'
import { getLyrics, getSong } from 'genius-lyrics-api'
import chalk from 'chalk'
import { getSong } from 'genius-lyrics-api'
import triggers from '../../resources/triggers.js'
import chalk from 'chalk'
const apiKey = process.env.GENIUS_KEY
/**
* Filters
@@ -40,21 +38,6 @@ function filter(lyrics) {
} else highlighted.push(word)
}
// for (let trigger of triggers) {
// let count = 0
// for (let word of words) {
// if (word.toLowerCase().match(trigger)) {
// count++
// console.log(word)
// highlighted.push(chalk.red(word))
// continue // only count first match
// } else highlighted.push(word)
// }
// if (count > 0) results[trigger] = count
// }
return {
lyrics,
results,
@@ -63,22 +46,13 @@ function filter(lyrics) {
}
}
function single(title = '', artist = '') {
return getLyrics({
apiKey,
optimizeQuery: true,
title,
artist,
})
}
async function info(title, artists) {
var out = { id: null, url: null, title: null, lyrics: null },
best = -1
for (let artist of artists) {
const result = await getSong({
apiKey,
apiKey: geniusKey,
optimizeQuery: true,
title,
artist: artist,
@@ -92,8 +66,6 @@ async function info(title, artists) {
})
).length
// console.log(result.title.split(' '), target)
result.match = match
if (match > best) {
@@ -108,4 +80,4 @@ async function info(title, artists) {
return out
}
export { single, filter, info }
export { filter, info }
+72
View File
@@ -0,0 +1,72 @@
import { offset } from '../../env.js'
import { durations, seconds } from './timings.js'
import { download } from './youtube.js'
import { logAction } from './log.js'
import Time from '../classes/Time.js'
function parse(tracks) {
let chart = durations.map(() => []),
n = 0
logAction(`Running parser`, tracks.length)
for (let i in durations) {
let total = 0
while (total < durations[i]) {
if (n >= tracks.length) break // end if tracks run out
total += tracks[n].duration / 1e3 // add track duration to current total
chart[i].push(tracks[n]) // add track to the chart
n++
}
}
return chart
}
function cache(chart) {
const tracks = chart.flat()
logAction(`Running caching`, `${tracks.length}`)
return Promise.all(tracks.map((track) => download(track))).then(
(paths) => chart
)
}
function scheduler(chart) {
let currentSeconds = Time.now() - offset,
schedule = [],
tracks = [],
ends = []
logAction(`Running scheduler`, `${seconds.length}`)
for (let nthPrzerwa in seconds) {
let [begin, end] = seconds[nthPrzerwa],
times = [],
subTracks = []
var tracktotal = 0
chart[nthPrzerwa].forEach((track, i) => {
tracktotal += (chart[nthPrzerwa][i - 1]?.duration ?? 0) / 1e3
let sched = new Time({ to: begin - currentSeconds + tracktotal })
times.push(sched)
subTracks.push(track)
})
let endin = new Time({ to: end - currentSeconds })
schedule.push(times)
tracks.push(subTracks)
ends.push(endin)
}
return { schedule, tracks, ends }
}
export { parse, cache, scheduler }
+12 -8
View File
@@ -1,4 +1,4 @@
import config from '../../env.js'
import { verbose } from '../../env.js'
import { spawn } from 'child_process'
@@ -8,8 +8,6 @@ class PlaybackError extends Error {
}
}
const verbose = Number(process.env.VERBOSE)
var radio,
busy = true,
waiting = []
@@ -17,10 +15,18 @@ var radio,
export default async function playback() {
radio = spawn('python', ['src/modules/radio.py'])
radio.stdin.setEncoding('utf-8')
radio.stdout.on('data', (data) => {
let lines = data.toString().split('\n')
for (let line of lines) {
let [status, ...data] = JSON.parse(line)
try {
var [status, ...data] = JSON.parse(line)
} catch (err) {
console.error('Invalid JSON from player')
console.error('Received: ', line)
throw err
}
verbose > 1 && console.info('¤ >', status, data)
@@ -39,10 +45,8 @@ export default async function playback() {
})
radio.on('close', (code) => {
throw `child process exited with code ${code}`
throw `vlc exited with code ${code}`
})
radio.stdin.setEncoding('utf-8')
}
function sendCommand(comm, data = [null]) {
@@ -71,4 +75,4 @@ const player = {
queueCommand('fade.in', [duration, target]),
}
export { player, queueCommand, sendCommand }
export { player, queueCommand }
+8 -4
View File
@@ -2,9 +2,10 @@ import spotifyToYt from 'spotify-to-yt'
import fs from 'fs'
import ytdl from 'ytdl-core'
import Track from '../classes/Track.js'
import { logAction, logError } from './log.js'
import Track from '../classes/Track.js'
const cache = './cache'
function convert(tids) {
@@ -36,7 +37,11 @@ function fetch(url, target, progress, end) {
}
let stream = ytdl(url, {
filter: 'audioonly',
filter: (format) => {
if (format.hasVideo) return false
if (format.container == 'mp4') return false
return true
},
}),
file = fs.createWriteStream(temp)
@@ -50,8 +55,7 @@ function fetch(url, target, progress, end) {
})
stream.on('end', () => {
file.close()
file.on('close', () => {
file.close(() => {
fs.renameSync(temp, final)
end(final, written)
resolve(final)
+3 -73
View File
@@ -1,18 +1,11 @@
import env from '../env.js'
import chalk from 'chalk'
import { defaultVolume, offset, verbose, limit } from '../env.js'
import playback, { player, queueCommand } from './modules/playback.js'
import { getTop, updateNext, updateStatus } from './modules/calls.js'
import { durations, seconds } from './modules/timings.js'
import { convert, download } from './modules/youtube.js'
import { convert } from './modules/youtube.js'
import { parse, cache, scheduler } from './modules/parse.js'
import { logAction, logSchedule, logTrack, logValue } from './modules/log.js'
import Time from './classes/Time.js'
const defaultVolume = parseInt(process.env.VOLUME_DEFAULT ?? 100),
offset = Number(process.env.OFFSET ?? 0),
verbose = Number(process.env.VERBOSE ?? 0),
limit = Number(process.env.LIMIT ?? 40)
function stream(track) {
queueCommand('change', [track.url])
@@ -27,69 +20,6 @@ function local(track) {
updateStatus(track.tid, 0, track.duration, false)
}
function parse(tracks) {
let chart = durations.map(() => []),
n = 0
logAction(`Running parser`, tracks.length)
for (let i in durations) {
let total = 0
while (total < durations[i]) {
if (n >= tracks.length) break // end if tracks run out
total += tracks[n].duration / 1e3 // add track duration to current total
chart[i].push(tracks[n]) // add track to the chart
n++
}
}
return chart
}
function cache(chart) {
const tracks = chart.flat()
logAction(`Running caching`, `${tracks.length}`)
return Promise.all(tracks.map((track) => download(track))).then(
(paths) => chart
)
}
function scheduler(chart) {
let currentSeconds = Time.now() - offset,
schedule = [],
tracks = [],
ends = []
logAction(`Running scheduler`, `${seconds.length}`)
for (let nthPrzerwa in seconds) {
let [begin, end] = seconds[nthPrzerwa],
times = [],
subTracks = []
var tracktotal = 0
chart[nthPrzerwa].forEach((track, i) => {
tracktotal += (chart[nthPrzerwa][i - 1]?.duration ?? 0) / 1e3
let sched = new Time({ to: begin - currentSeconds + tracktotal })
times.push(sched)
subTracks.push(track)
})
let endin = new Time({ to: end - currentSeconds })
schedule.push(times)
tracks.push(subTracks)
ends.push(endin)
}
return { schedule, tracks, ends }
}
export default async function standalone() {
logValue('Volume', defaultVolume)
logValue('Offset', offset)
+1 -2
View File
@@ -3,8 +3,7 @@ import yesno from 'yesno'
import { getTop, getTrack } from './modules/calls.js'
import { logAction, logTrack, logValue } from './modules/log.js'
import { single, filter, info } from './modules/lyrics.js'
import { convert } from './modules/youtube.js'
import { filter, info } from './modules/lyrics.js'
const lowWordCount = 190