From 00fc7895763dffce61d24fe0cdbc5a9bda242c8f Mon Sep 17 00:00:00 2001 From: Mateusz Pstrucha Date: Tue, 30 Nov 2021 17:53:21 +0100 Subject: [PATCH] fix: treeshaking --- env.js | 16 +++++++++ purge | 2 ++ src/modules/calls.js | 15 ++++---- src/modules/log.js | 4 +-- src/modules/lyrics.js | 38 +++------------------ src/modules/parse.js | 72 ++++++++++++++++++++++++++++++++++++++ src/modules/playback.js | 20 ++++++----- src/modules/youtube.js | 12 ++++--- src/standalone.js | 76 ++--------------------------------------- src/words.js | 3 +- 10 files changed, 127 insertions(+), 131 deletions(-) create mode 100644 purge create mode 100644 src/modules/parse.js diff --git a/env.js b/env.js index c568957..9bf5930 100644 --- a/env.js +++ b/env.js @@ -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, +} diff --git a/purge b/purge new file mode 100644 index 0000000..2d1e848 --- /dev/null +++ b/purge @@ -0,0 +1,2 @@ +find cache/* -mtime +7 +find cache/* -mtime +7 -exec rm {} \; \ No newline at end of file diff --git a/src/modules/calls.js b/src/modules/calls.js index 6f6108f..3de9e7a 100644 --- a/src/modules/calls.js +++ b/src/modules/calls.js @@ -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 } diff --git a/src/modules/log.js b/src/modules/log.js index 722d0bb..587e707 100644 --- a/src/modules/log.js +++ b/src/modules/log.js @@ -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) { diff --git a/src/modules/lyrics.js b/src/modules/lyrics.js index 0dc03cd..f996f99 100644 --- a/src/modules/lyrics.js +++ b/src/modules/lyrics.js @@ -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 } diff --git a/src/modules/parse.js b/src/modules/parse.js new file mode 100644 index 0000000..400193b --- /dev/null +++ b/src/modules/parse.js @@ -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 } diff --git a/src/modules/playback.js b/src/modules/playback.js index 4c5410b..647a9f8 100644 --- a/src/modules/playback.js +++ b/src/modules/playback.js @@ -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 } diff --git a/src/modules/youtube.js b/src/modules/youtube.js index f0bbeb3..438380f 100644 --- a/src/modules/youtube.js +++ b/src/modules/youtube.js @@ -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) diff --git a/src/standalone.js b/src/standalone.js index 60c18c7..ea77c23 100644 --- a/src/standalone.js +++ b/src/standalone.js @@ -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) diff --git a/src/words.js b/src/words.js index 60d7f8c..7683281 100644 --- a/src/words.js +++ b/src/words.js @@ -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