refactor: dump

This commit is contained in:
Mateusz Pstrucha committed 2021-11-29 23:59:30 +01:00
1 parent 790144fecc
commit 9173e5b466
24 files changed
+2417 -349

No files matched your search

+2 -1
View File
@@ -1,3 +1,4 @@
__pycache__
node_modules/
.env
.env
cache/
+2 -2
View File
@@ -12,8 +12,8 @@ API - https://github.com/Maathias/radio-rolnik-api/
- VLC
- python3
- python
- dotenv
- vlc
- python-dotenv
- python-vlc
- pafy
- youtube_dl
+66 -139
View File
@@ -1,152 +1,79 @@
import env from './env.js'
import chalk from 'chalk'
import yargs from 'yargs'
import { getTop } from './src/modules/calls.js'
import { logTrack } from './src/modules/log.js'
import { convert } from './src/modules/youtube.js'
import { player, queueCommand } from './modules/playback.js'
import { getTop, updateNext, updateStatus } from './modules/calls.js'
import { now, durations, seconds } from './modules/timings.js'
import standalone from './src/standalone.js'
import words, { one } from './src/words.js'
import Track from './Track.js'
// Check Node version
const defaultVolume = parseInt(process.env.VOLUME_DEFAULT ?? 100),
offset = Number(process.env.OFFSET ?? 0),
verbose = Number(process.env.VERBOSE ?? 0)
const [minMajor, minMinor] = [16, 13],
[major, minor] = process.version.slice(1).split('.')
function play(track) {
queueCommand('change', [track.url])
player.play()
queueCommand('volume', [defaultVolume])
updateStatus(track.tid, 0, track.duration, false)
if (major < minMajor || minor < minMinor) {
console.error(
`Node ${minMajor}.${minMinor} reqired. Running ${major}.${minor}`
)
process.exit(1)
}
function sToHM(seconds) {
let h = ~~(seconds / 3600),
m = ~~((seconds - h * 3600) / 60)
// Parse arguments
return [h, m]
}
const args = yargs(process.argv.slice(2))
.option('tid', {
alias: 'T',
})
.option('tids', {
type: 'array',
default: [],
})
.option('sus', {
alias: 's',
type: 'boolean',
})
.option('title', {
alias: 't',
type: 'array',
default: [],
})
.option('artists', {
alias: 'a',
type: 'array',
default: [],
}).argv
function pad(n) {
return n < 10 ? '0' + n : n
}
// console.log(args)
console.info(
`Volume: ${chalk.yellow(defaultVolume)}, Verbose: ${chalk.yellow(
verbose
)}, Limit: ${chalk.yellow(process.env.LIMIT)}`
)
switch (args._[0]) {
default:
console.log('Defaulting to Web module')
case 'web':
web()
break
case 'standalone':
standalone()
break
case 'lyrics':
if (args.T || args.t.length > 0 || args.a.length > 0) {
let tid = args.T,
title = args.t.join(' '),
artists = args.a.join(' ')
console.info(`Fetching playlist (${chalk.yellow(process.env.DOMAIN)})`)
getTop()
.then(async (data) => {
console.info(`Parsing playlist`)
let schedule = durations.map(() => [])
const top = data.map((tdata) => new Track(tdata))
let n = 0
for (let i in durations) {
let total = 0
while (total < durations[i]) {
if (n >= top.length) break
total += top[n].duration / 1e3
schedule[i].push(top[n])
n++
if (tid) {
one({ tid })
} else if (title && artists) {
one({ title, artists })
}
}
} else words({ sus: args.s || args.banned })
break
case 'convert':
let tid = args.T ? [args.T] : args.tids
return schedule
})
.catch((err) => {
throw err
})
.then((schedule) => {
let currentSeconds = now() - offset
console.info(
`Running track scheduler @${new Date().toLocaleTimeString()} +${chalk.yellow(
offset
)}s`
)
for (let nthPrzerwa in seconds) {
let [begin, end] = seconds[nthPrzerwa]
var tracktotal = 0
console.info(chalk.green(`\nPrzerwa #${nthPrzerwa}`))
schedule[nthPrzerwa].forEach((track, i) => {
tracktotal += (schedule[nthPrzerwa][i - 1]?.duration ?? 0) / 1e3
let sched = begin - currentSeconds + tracktotal
let [h, m] = sToHM(currentSeconds + sched)
console.info(
`scheduling ${track.tid} @ ${chalk.red(
`${h}:${pad(m)}`
)} in ${sched}s`
)
console.info(
`╚═ (${chalk.cyan((track.duration / 60e3).toFixed(1))}) [${chalk.blue(
track.title.slice(0, 50)
)}]`
)
if (sched < -10) return
setTimeout(() => {
console.info(
`${chalk.magenta(`${h}:${pad(m)}`)} playing ${track.tid} (${
track.ytid
})`
)
console.info(
` ╚ (${chalk.cyan(
(track.duration / 60e3).toFixed(1)
)}) ${chalk.blue(track.title.slice(0, 50))} `
)
play(track)
updateNext(schedule[nthPrzerwa][i + 1]?.tid ?? null)
}, sched * 1e3)
convert(tid).then((tracks) => {
tracks.forEach((track) => {
logTrack(track)
})
verbose > 0 &&
setTimeout(() => {
console.info(`Beginning of #${nthPrzerwa} in 10s`)
}, (begin - currentSeconds) * 1e3 - 10e3)
let endin = end - currentSeconds,
[h, m] = sToHM(end)
console.info(`» End of playback #${nthPrzerwa} @ ${h}:${pad(m)}`)
if (nthPrzerwa == seconds.length - 1) {
setTimeout(() => {
console.info(`≡≡≡ Day Ended ≡≡≡`)
setTimeout(() => {
process.exit(0)
}, 10e3)
}, endin * 1e3)
}
if (endin < 0) continue
setTimeout(() => {
console.info(`« Ending playback for #${nthPrzerwa} »\n`)
player.fadeOut(6)
updateStatus(null, null, null, true)
}, endin * 1e3)
}
player.pause()
console.info(`\nTrack scheduling done`)
console.info(`─────────────────────────`)
})
})
break
}
-42
View File
@@ -1,42 +0,0 @@
import chalk from 'chalk'
import { getTop, getTrack } from './modules/calls.js'
import { single, filter } from './modules/lyrics.js'
const lowWordCount = 190
getTop('rolling').then(async (top) => {
for (let { tid } of top) {
let { title, artists } = await getTrack(tid)
single(title, artists[0])
.then(filter)
.then(({ lyrics, results, wordCount }) => {
let keys = results ? Object.keys(results) : 0
if (keys.length > 0) {
// trigger words found
console.log(
`${chalk.red(`${tid} ${title} : ${artists}`)}: ${chalk.magenta(
keys
.map((trigger) => `${trigger} x${results[trigger]}`)
.join(', ')
)}`
)
} else if (lyrics == null) {
// no lyrics found
console.log(
`${chalk.yellow(`${tid} ${title} : ${artists}`)}, no lyrics`
)
} else if (wordCount <= lowWordCount) {
// low word count
console.log(
`${chalk.cyan(`${tid} ${title} : ${artists}`)}, ${wordCount} words`
)
} else {
// all good
console.log(chalk.green(`${tid} ${title} : ${artists}`))
}
})
}
})
-48
View File
@@ -1,48 +0,0 @@
import env from '../env.js'
import { getLyrics } from 'genius-lyrics-api'
import triggers from '../resources/words.js'
const apiKey = process.env.GENIUS_KEY
/**
* Filters
* @param {String} lyrics Track lyrics to be filtered
* @returns {Object.lyrics}
*/
function filter(lyrics) {
// lyrics not found
if (lyrics === null) {
return { lyrics }
}
// split into words
let words = lyrics.split(/[\n\s]/),
results = {}
for (let trigger of triggers) {
let count = 0
for (let word of words) {
if (word.toLowerCase().match(trigger)) {
count++
continue // only count first match
}
}
if (count > 0) results[trigger] = count
}
return { lyrics, results, wordCount: words.length }
}
function single(title = '', artist = '') {
return getLyrics({
apiKey,
optimizeQuery: true,
title,
artist,
})
}
export { single, filter }
-65
View File
@@ -1,65 +0,0 @@
import { spawn } from 'child_process'
import dotenv from 'dotenv'
dotenv.config()
const radio = spawn('python', ['modules/radio.py']),
verbose = Number(process.env.VERBOSE)
var busy = true,
waiting = []
radio.stdout.on('data', (data) => {
let lines = data.toString().split('\n')
for (let line of lines) {
let [status, ...data] = JSON.parse(line)
verbose > 0 && console.info(' < ', status, data)
if (status == 'waiting')
if (data[0]) {
busy = false
if (waiting.length > 0) {
waiting.shift().resolve()
}
}
}
})
radio.stderr.on('data', (data) => {
throw data.toString()
})
radio.on('close', (code) => {
throw `child process exited with code ${code}`
})
function sendCommand(comm, data = [null]) {
verbose > 1 && console.info(' > ', comm, data)
busy = true
radio.stdin.write(JSON.stringify(['command', comm, ...data]) + '\n')
}
function queueCommand(comm, data) {
if (busy) {
new Promise((resolve, reject) => {
waiting.push({ resolve, reject })
}).then(() => {
sendCommand(comm, data)
})
} else sendCommand(comm, data)
}
radio.stdin.setEncoding('utf-8')
const player = {
play: () => queueCommand('play'),
pause: () => queueCommand('pause'),
stop: () => queueCommand('stop'),
volume: (vol) => queueCommand('volume', [vol]),
fadeOut: (duration = 3) => queueCommand('fade.out', [duration]),
fadeIn: (duration = 3, target = 75) =>
queueCommand('fade.in', [duration, target]),
}
export { player, queueCommand, sendCommand }
-17
View File
@@ -1,17 +0,0 @@
import timings from '../przerwy.js'
const seconds = timings.map((przerwa) =>
przerwa.map(([h, m]) => h * 60 * 60 + m * 60)
)
const durations = seconds.map(([start, end]) => end - start)
export { timings, seconds, durations }
function now() {
let now = new Date()
return now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds()
}
export { now }
+1705 -3
View File
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -24,6 +24,9 @@
"got": "^11.8.2",
"ky": "^0.28.5",
"spotify-to-yt": "^1.0.5",
"youtube-sr": "4.1.7"
"yargs": "^17.2.1",
"yesno": "^0.3.1",
"youtube-sr": "4.1.7",
"ytdl-core": "^4.9.1"
}
}
View File
File renamed without changes.
@@ -48,6 +48,7 @@ export default [
'dupa',
'dupie',
'dupą',
'dupom',
'dupcia',
'dupeczka',
'dupy',
+1 -1
View File
@@ -1 +1 @@
node index.js
node index.js $@
+42
View File
@@ -0,0 +1,42 @@
function pad(n) {
return n < 10 ? '0' + n : n.toString()
}
class Time extends Date {
constructor({ to, at, hms: { hours, minutes, seconds = 0 } = {} }) {
super()
if (to) {
let at = Time.now() + to,
hours = Math.floor(at / 3600),
minutes = Math.floor((at - hours * 3600) / 60),
seconds = (at - hours * 3600) % 60
this.setHours(hours, minutes, seconds, 0)
}
}
to() {
return this.at() - Time.now()
}
at() {
return this.getHours() * 3600 + this.getMinutes() * 60 + this.getSeconds()
}
hms() {
return {
h: this.getHours().toString(),
m: pad(this.getMinutes()),
s: pad(this.getSeconds()),
}
}
static now() {
let now = new Date()
return now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds()
}
}
export default Time
+1 -1
View File
@@ -1,5 +1,5 @@
class Track {
constructor({ url, tid, info: [{ id, title, duration }] }) {
constructor(tid, { url, info: [{ id, title, duration }] }) {
this.url = url
this.tid = tid
this.ytid = id
+15 -29
View File
@@ -1,12 +1,13 @@
import env from '../env.js'
import env 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),
limit = Number(process.env.LIMIT ?? 40)
verbose = Number(process.env.VERBOSE)
function updateStatus(tid, progress, duration, paused) {
return new Promise((resolve, reject) => {
@@ -44,32 +45,17 @@ function updateNext(tid) {
}
function getTop(mode = 'once') {
return new Promise((resolve, reject) => {
verbose > 1 && console.info(`GET top`)
got
.get(`https://${DOMAIN}/api/player/get/top?mode=${mode}`, {
headers,
})
.json()
.then((top) => {
console.info(
`Resolving ${chalk.cyan(
top.length > limit ? limit + '/' + top.length : top.length
)} tracks`
)
Promise.all(
top
.slice(0, limit)
.map((tid) => spotifyToYt.trackGet(`spotify:track:${tid}`))
).then((yts) => {
top.slice(0, limit).map((tid, i) => {
yts[i].tid = tid
})
resolve(yts)
})
})
.catch((err) => reject(err))
})
logAction(`Fetching tids`, mode)
return got
.get(`https://${DOMAIN}/api/player/get/top?mode=${mode}`, {
headers,
})
.json()
.then((tids) => {
logValue('Tracks', tids.length)
return tids
})
}
function getTrack(tid) {
+39
View File
@@ -0,0 +1,39 @@
import chalk from 'chalk'
function logValue(label, value) {
console.info(label + ':', chalk.yellow(value))
}
function logAction(label, value = '') {
console.info(chalk.bold(label), chalk.yellow(value))
}
function logError(label, value) {
console.info(chalk.red(`§ ${label}`), value)
}
function logSchedule(time, label) {
let { h, m, s } = time.hms()
console.info(
`${label ? '»»» ' + chalk.yellow(label) : ' Ø'} ${(time.to() > 0
? chalk.green
: chalk.cyan)(`${h}:${m}:${s}`)} (in ${time.to()}s)`,
(label && '\n') || ''
)
}
function logTrack(track, { color = 'blue', meta = '' } = {}) {
console.info(` ╔ ${chalk[color](track.title.slice(0, 50))}`)
if (meta) console.info(` ║ ${meta}`)
console.info(
` ╚ ${
track.duration
? `(${chalk.cyan((track.duration / 60e3).toFixed(1))})`
: ''
} ${chalk.gray(`${track.tid ?? ''} . ${track.ytid ?? ''}`)} `
)
}
export { logValue, logAction, logError, logSchedule, logTrack }
+111
View File
@@ -0,0 +1,111 @@
import env from '../../env.js'
import { getLyrics, getSong } from 'genius-lyrics-api'
import triggers from '../../resources/triggers.js'
import chalk from 'chalk'
const apiKey = process.env.GENIUS_KEY
/**
* Filters
* @param {String} lyrics Track lyrics to be filtered
* @returns {Object.lyrics}
*/
function filter(lyrics) {
// lyrics not found
if (lyrics === null) {
return { lyrics }
}
// split into words
let words = lyrics.replace(/\n/g, '&n').split(/[\n\s]/),
results = {},
highlighted = []
function check(word) {
for (let trigger of triggers) {
if (word.toLowerCase().match(trigger)) return trigger
}
return false
}
for (let word of words) {
let trigger = check(word)
if (trigger) {
if (!results[trigger]) results[trigger] = 1
else results[trigger]++
highlighted.push(chalk.red(word))
} 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,
wordCount: words.length,
highlighted: highlighted.join(' ').replace(/&n/g, '\n'),
}
}
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,
optimizeQuery: true,
title,
artist: artist,
}),
target = title.split(' ')
if (result) {
let match = result.title.split(' ').filter((word) =>
target.some((tword) => {
return word.toLowerCase().includes(tword.toLowerCase())
})
).length
// console.log(result.title.split(' '), target)
result.match = match
if (match > best) {
best = match
out = result
}
if (match == target.length) break
}
}
return out
}
export { single, filter, info }
+74
View File
@@ -0,0 +1,74 @@
import config from '../../env.js'
import { spawn } from 'child_process'
class PlaybackError extends Error {
constructor(message = '', ...args) {
super(message, ...args)
}
}
const verbose = Number(process.env.VERBOSE)
var radio,
busy = true,
waiting = []
export default async function playback() {
radio = spawn('python', ['src/modules/radio.py'])
radio.stdout.on('data', (data) => {
let lines = data.toString().split('\n')
for (let line of lines) {
let [status, ...data] = JSON.parse(line)
verbose > 1 && console.info('¤ >', status, data)
if (status == 'waiting')
if (data[0]) {
busy = false
if (waiting.length > 0) {
waiting.shift().resolve()
}
}
}
})
radio.stderr.on('data', (data) => {
throw new PlaybackError(data.toString())
})
radio.on('close', (code) => {
throw `child process exited with code ${code}`
})
radio.stdin.setEncoding('utf-8')
}
function sendCommand(comm, data = [null]) {
verbose > 1 && console.info('¤ <', comm, data)
busy = true
radio.stdin.write(JSON.stringify(['command', comm, ...data]) + '\n')
}
function queueCommand(comm, data) {
if (busy) {
new Promise((resolve, reject) => {
waiting.push({ resolve, reject })
}).then(() => {
sendCommand(comm, data)
})
} else sendCommand(comm, data)
}
const player = {
play: () => queueCommand('play'),
pause: () => queueCommand('pause'),
stop: () => queueCommand('stop'),
volume: (vol) => queueCommand('volume', [vol]),
fadeOut: (duration = 3) => queueCommand('fade.out', [duration]),
fadeIn: (duration = 3, target = 75) =>
queueCommand('fade.in', [duration, target]),
}
export { player, queueCommand, sendCommand }
@@ -98,6 +98,14 @@ def change(args):
info('change', ['done', target])
def local(args):
file, *args = args
Media = Instance.media_new_path(file)
player.set_media(Media)
info('local', ['done', file])
def stop(args=[]):
player.stop()
info('stop', ['done'])
@@ -109,6 +117,7 @@ def what(comm):
"pause": pause,
"stop": stop,
"change": change,
"local": local,
"volume": volume,
"fade.out": fadeOut,
"fade.in": fadeIn,
+13
View File
@@ -0,0 +1,13 @@
import Time from '../classes/Time.js'
import timings from '../../resources/przerwy.js'
const seconds = timings.map((przerwa) =>
przerwa.map(([h, m]) => h * 60 * 60 + m * 60)
)
const durations = seconds.map(([start, end]) => end - start)
const times = timings.map((przerwa) => przerwa.map(([h, m]) => new Time(h, m)))
export { timings, seconds, durations, times }
+85
View File
@@ -0,0 +1,85 @@
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'
const cache = './cache'
function convert(tids) {
logAction(`Running converter`, tids.length)
return Promise.all(
tids.map((tid) =>
spotifyToYt.trackGet(`spotify:track:${tid}`).catch((err) => {
logError(`Conversion failed, retrying`, tid)
return spotifyToYt.trackGet(`spotify:track:${tid}`).catch((err2) => {
logError(`Conversion failed twice, I give up`, tid)
throw err2
})
})
)
).then((ytd) => {
return tids.map((tid, i) => new Track(tid, ytd[i]))
})
}
function fetch(url, target, progress, end) {
return new Promise((resolve, reject) => {
const temp = target + '.tmp',
final = target
if (!fs.existsSync(cache)) {
fs.mkdirSync(cache)
}
let stream = ytdl(url, {
filter: 'audioonly',
}),
file = fs.createWriteStream(temp)
let written = 0
stream.on('data', (data) => {
file.write(data, () => {
written += data.length
progress(data.length, written)
})
})
stream.on('end', () => {
file.close()
file.on('close', () => {
fs.renameSync(temp, final)
end(final, written)
resolve(final)
})
})
})
}
async function download(track) {
const target = `${cache}/${track.tid}.mp4`
if (fs.existsSync(target)) return target
return await fetch(
track.url,
target,
(chunk, total) => {
process.stdout.clearLine()
process.stdout.cursorTo(0)
process.stdout.write(`${track.tid} ${(total / 1024).toFixed(0)}KB`)
},
() => {
console.log()
}
).then((final) => {
console.info(`downloaded`, final)
return final
})
}
export { convert, download }
+144
View File
@@ -0,0 +1,144 @@
import env from '../env.js'
import chalk from 'chalk'
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 { 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])
player.play()
queueCommand('volume', [defaultVolume])
updateStatus(track.tid, 0, track.duration, false)
}
function local(track) {
queueCommand('local', [`./cache/${track.tid}.mp4`])
player.play()
queueCommand('volume', [defaultVolume])
}
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)
logValue('Verbose', verbose)
logValue('Limit', process.env.LIMIT)
const { schedule, tracks, ends } = await getTop() // tids
.then((tids) => tids.slice(0, limit))
.then(convert) // Tracks
.then(parse) // chart
.then(cache)
.then(scheduler) // schedule
for (let przerwa in schedule) {
let _tracks = tracks[przerwa],
_times = schedule[przerwa],
end = ends[przerwa]
for (let n in _tracks) {
let track = _tracks[n],
starts = _times[n]
// schedule TRACK
logSchedule(starts)
logTrack(track)
if (starts.to() > -10)
setTimeout(() => {
logAction(` ╔ « Playing »`)
logTrack(track)
local(track)
}, starts.to() * 1e3)
}
// schedule END
logSchedule(end, `#${przerwa} End`)
if (end.to() >= 0)
setTimeout(() => {
logAction(`» End of #${przerwa} «`)
player.fadeOut(6)
}, end.to() * 1e3)
}
setTimeout(() => {
logAction('≡≡≡ End of the day ≡≡≡')
process.exit(0)
}, (ends.at(-1).to() + 10) * 1e3)
logAction('Starting player')
playback()
}
+1
View File
@@ -0,0 +1 @@
export default function web() {}
+102
View File
@@ -0,0 +1,102 @@
import chalk from 'chalk'
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'
const lowWordCount = 190
async function one({ title, artists, tid }) {
if (tid) {
logAction('Resolving tid')
var { title, artists } = await getTrack(tid)
}
logValue('Title', title)
logValue('Artists', artists)
logAction('Getting Track')
const {
id: gid,
title: gTitle,
url,
lyrics,
match,
} = await info(title, artists)
logValue('Genius ID', gid)
logValue('Title', gTitle)
logValue('Title match', match)
logValue('Url', url)
logAction('Running filter')
const { results, wordCount, highlighted } = filter(lyrics)
logValue('Word count', wordCount)
for (let trigger in results) {
let count = results[trigger]
console.info(count > 1 ? chalk.red('x' + count) : ' ', trigger)
}
let display = await yesno({
question: 'Display lyrics?',
defaultValue: false,
})
console.log()
if (display) console.info(highlighted)
return 0
}
export { one }
export default function words({ sus, rolling }) {
return getTop(rolling ? 'rolling' : 'once').then(async (top) => {
for (let tid of top.slice(20)) {
const { title, artists } = await getTrack(tid)
info(title, artists).then(({ title: gTitle, lyrics, match }) => {
const { results, wordCount, fLyrics } = filter(lyrics)
let keys = results ? Object.keys(results) : 0
let track = {
tid,
title: gTitle || title,
},
options = {
color: 'green',
}
if (keys.length > 0) {
// trigger words found
options.color = 'red'
options.meta = keys
.map((trigger) => `${trigger} x${results[trigger]}`)
.join(', ')
} else if (match < 1) {
// title mismatch
options.color = 'magenta'
options.meta = `title mismatch: ${title}`
} else if (wordCount <= lowWordCount) {
// low word count
options.color = 'cyan'
options.meta = `low word count: ${wordCount}`
} else if (lyrics == null) {
// no lyrics found
options.color = 'yellow'
options.meta = ' no lyrics found'
} else {
if (sus) return
}
logTrack(track, options)
})
}
})
}