Major refactor #4
No files matched your search
+2
-1
@@ -1,3 +1,4 @@
|
||||
__pycache__
|
||||
node_modules/
|
||||
.env
|
||||
.env
|
||||
cache/
|
||||
@@ -12,8 +12,8 @@ API - https://github.com/Maathias/radio-rolnik-api/
|
||||
- VLC
|
||||
- python3
|
||||
- python
|
||||
- dotenv
|
||||
- vlc
|
||||
- python-dotenv
|
||||
- python-vlc
|
||||
- pafy
|
||||
- youtube_dl
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -1,152 +1,115 @@
|
||||
import env from './env.js'
|
||||
import chalk from 'chalk'
|
||||
import yargs from 'yargs'
|
||||
import { readFileSync } from 'fs'
|
||||
|
||||
import { player, queueCommand } from './modules/playback.js'
|
||||
import { getTop, updateNext, updateStatus } from './modules/calls.js'
|
||||
import { now, durations, seconds } from './modules/timings.js'
|
||||
import web from './src/web.js'
|
||||
import cache from './src/cache.js'
|
||||
import schedule from './src/schedule.js'
|
||||
import standalone from './src/standalone.js'
|
||||
import test from './src/test.js'
|
||||
import words, { one } from './src/words.js'
|
||||
|
||||
import Track from './Track.js'
|
||||
import { logAction, logTrack } from './src/modules/log.js'
|
||||
import { convert } from './src/modules/youtube.js'
|
||||
|
||||
const defaultVolume = parseInt(process.env.VOLUME_DEFAULT ?? 100),
|
||||
offset = Number(process.env.OFFSET ?? 0),
|
||||
verbose = Number(process.env.VERBOSE ?? 0)
|
||||
// Check Node version
|
||||
|
||||
function play(track) {
|
||||
queueCommand('change', [track.url])
|
||||
player.play()
|
||||
queueCommand('volume', [defaultVolume])
|
||||
updateStatus(track.tid, 0, track.duration, false)
|
||||
const [minMajor, minMinor] = [16, 13],
|
||||
[major, minor] = process.version.slice(1).split('.')
|
||||
|
||||
if (major < minMajor || (major == minMajor && minor < minMinor)) {
|
||||
console.error(
|
||||
`Node ${minMajor}.${minMinor} reqired. Running ${major}.${minor}`
|
||||
)
|
||||
process.exit(1)
|
||||
} else {
|
||||
}
|
||||
|
||||
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('rolling', {
|
||||
alias: 'r',
|
||||
type: 'boolean',
|
||||
})
|
||||
.option('missing', {
|
||||
alias: 'm',
|
||||
type: 'boolean',
|
||||
})
|
||||
.option('cache', {
|
||||
alias: 'c',
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
})
|
||||
.option('tid', {
|
||||
alias: 'T',
|
||||
})
|
||||
.option('tids', {
|
||||
type: 'array',
|
||||
default: [],
|
||||
})
|
||||
.option('sus', {
|
||||
alias: 's',
|
||||
type: 'boolean',
|
||||
})
|
||||
.option('title', {
|
||||
alias: 't',
|
||||
type: 'array',
|
||||
default: [],
|
||||
})
|
||||
.option('playlist', {
|
||||
alias: 'p',
|
||||
type: 'string',
|
||||
})
|
||||
.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 standalone')
|
||||
case 'standalone':
|
||||
standalone({ rolling: args.r })
|
||||
break
|
||||
case 'web':
|
||||
web()
|
||||
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({ susOnly: 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
|
||||
case 'cache':
|
||||
cache({ missingOnly: args.m })
|
||||
break
|
||||
case 'schedule':
|
||||
schedule({ checkCache: args.c, rolling: args.r })
|
||||
break
|
||||
case 'test':
|
||||
test()
|
||||
case 'playlist':
|
||||
logAction('Reading playlist', args.p)
|
||||
const tids = JSON.parse(readFileSync(`./${args.p}.json`))
|
||||
standalone({ tids })
|
||||
break
|
||||
}
|
||||
@@ -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}`))
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -1,79 +0,0 @@
|
||||
import env from '../env.js'
|
||||
import chalk from 'chalk'
|
||||
import got from 'got'
|
||||
import spotifyToYt from 'spotify-to-yt'
|
||||
|
||||
const { DOMAIN, SECRET } = process.env,
|
||||
headers = { authorization: 'Bearer ' + SECRET },
|
||||
verbose = Number(process.env.VERBOSE),
|
||||
limit = Number(process.env.LIMIT ?? 40)
|
||||
|
||||
function updateStatus(tid, progress, duration, paused) {
|
||||
return new Promise((resolve, reject) => {
|
||||
verbose > 1 && console.info(`PUT status`, tid, progress, duration, paused)
|
||||
got
|
||||
.put(`https://${DOMAIN}/api/player/set/status`, {
|
||||
headers,
|
||||
json: {
|
||||
tid,
|
||||
progress,
|
||||
duration,
|
||||
paused,
|
||||
},
|
||||
})
|
||||
.json()
|
||||
.then((ok) => resolve(ok))
|
||||
.catch((err) => reject(err))
|
||||
})
|
||||
}
|
||||
|
||||
function updateNext(tid) {
|
||||
return new Promise((resolve, reject) => {
|
||||
verbose > 1 && console.info(`PUT next`, tid)
|
||||
got
|
||||
.put(`https://${DOMAIN}/api/player/set/next`, {
|
||||
headers,
|
||||
json: {
|
||||
tid,
|
||||
},
|
||||
})
|
||||
.json()
|
||||
.then((ok) => resolve(ok))
|
||||
.catch((err) => reject(err))
|
||||
})
|
||||
}
|
||||
|
||||
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))
|
||||
})
|
||||
}
|
||||
|
||||
function getTrack(tid) {
|
||||
return got.get(`https://${DOMAIN}/api/track/${tid}`).json()
|
||||
}
|
||||
|
||||
export { updateStatus, updateNext, getTop, getTrack }
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
Generated
+1705
-3
File diff suppressed because it is too large.
Load diff
+4
-1
@@ -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"
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -48,6 +48,7 @@ export default [
|
||||
'dupa',
|
||||
'dupie',
|
||||
'dupą',
|
||||
'dupom',
|
||||
'dupcia',
|
||||
'dupeczka',
|
||||
'dupy',
|
||||
@@ -0,0 +1,50 @@
|
||||
import { limit } from '../env.js'
|
||||
|
||||
import yesno from 'yesno'
|
||||
|
||||
import { getTop } from './modules/calls.js'
|
||||
import { convert, download, check } from './modules/youtube.js'
|
||||
import { parse } from './modules/parse.js'
|
||||
import { logTrack } from './modules/log.js'
|
||||
import Time from './classes/Time.js'
|
||||
|
||||
export default async function cache({ missingOnly }) {
|
||||
const tracks = await getTop() // tids
|
||||
.then((tids) => tids.slice(0, limit))
|
||||
.then(convert) // Tracks
|
||||
.then(parse) // chart
|
||||
.then((chart) => chart.flat()) // Tracks
|
||||
|
||||
let missing = []
|
||||
|
||||
for (let track of tracks) {
|
||||
const target = `./cache/${track.tid}.mp4`
|
||||
|
||||
const { size, daysAgo } = check(target)
|
||||
|
||||
if (size) {
|
||||
if (missingOnly) continue
|
||||
|
||||
logTrack(track, {
|
||||
color: daysAgo >= 7 ? 'magenta' : 'green',
|
||||
meta: `${(size / 1000 / 1000).toFixed(1)}MB used ${daysAgo.toFixed(
|
||||
0
|
||||
)} days ago`,
|
||||
})
|
||||
} else {
|
||||
logTrack(track, { color: 'red', meta: 'Not cached' })
|
||||
missing.push(track)
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.length > 0)
|
||||
if (
|
||||
await yesno({
|
||||
question: `Download ${missing.length} missing tracks?`,
|
||||
defaultValue: false,
|
||||
})
|
||||
)
|
||||
for (let track of missing) {
|
||||
download(track)
|
||||
}
|
||||
}
|
||||
@@ -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,6 +1,6 @@
|
||||
class Track {
|
||||
constructor({ url, tid, info: [{ id, title, duration }] }) {
|
||||
this.url = url
|
||||
constructor(tid, [{ id, title, duration }]) {
|
||||
this.url = `https://www.youtube.com/watch?v=${id}`
|
||||
this.tid = tid
|
||||
this.ytid = id
|
||||
this.title = title
|
||||
@@ -0,0 +1,71 @@
|
||||
import { domain, secret, verbose } from '../../env.js'
|
||||
|
||||
import got from 'got'
|
||||
|
||||
import { logAction, logValue } from './log.js'
|
||||
|
||||
const headers = { authorization: 'Bearer ' + secret }
|
||||
|
||||
function updateStatus(track, progress = null, duration = null, paused) {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log({
|
||||
tid: track?.tid ?? null,
|
||||
progress,
|
||||
duration,
|
||||
paused: paused ?? track ? false : true,
|
||||
})
|
||||
got
|
||||
.put(`https://${domain}/api/player/set/status`, {
|
||||
headers,
|
||||
json: {
|
||||
tid: track?.tid ?? null,
|
||||
progress,
|
||||
duration,
|
||||
paused: paused ?? track ? false : true,
|
||||
},
|
||||
})
|
||||
.json()
|
||||
.then((ok) => resolve(ok))
|
||||
.catch((err) => reject(err))
|
||||
|
||||
verbose > 1 &&
|
||||
console.info(`PUT status`, track?.tid, progress, duration, paused)
|
||||
})
|
||||
}
|
||||
|
||||
function updateNext(track) {
|
||||
return new Promise((resolve, reject) => {
|
||||
got
|
||||
.put(`https://${domain}/api/player/set/next`, {
|
||||
headers,
|
||||
json: {
|
||||
tid: track ? track.tid : null,
|
||||
},
|
||||
})
|
||||
.json()
|
||||
.then((ok) => resolve(ok))
|
||||
.catch((err) => reject(err))
|
||||
|
||||
verbose > 1 && console.info(`PUT next`, track?.tid)
|
||||
})
|
||||
}
|
||||
|
||||
function getTop(mode = 'once') {
|
||||
logAction(`Fetching tids`, mode, domain)
|
||||
|
||||
return got
|
||||
.get(`https://${domain}/api/player/get/top?mode=${mode}`, {
|
||||
headers,
|
||||
})
|
||||
.json()
|
||||
.then((tids) => {
|
||||
logValue('Tracks', tids.length)
|
||||
return tids
|
||||
})
|
||||
}
|
||||
|
||||
function getTrack(tid) {
|
||||
return got.get(`https://${domain}/api/track/${tid}`).json()
|
||||
}
|
||||
|
||||
export { updateStatus, updateNext, getTop, getTrack }
|
||||
@@ -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.join(' ')))
|
||||
}
|
||||
|
||||
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 }
|
||||
@@ -0,0 +1,83 @@
|
||||
import { geniusKey } from '../../env.js'
|
||||
|
||||
import chalk from 'chalk'
|
||||
import { getSong } from 'genius-lyrics-api'
|
||||
|
||||
import triggers from '../../resources/triggers.js'
|
||||
|
||||
/**
|
||||
* 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)
|
||||
}
|
||||
|
||||
return {
|
||||
lyrics,
|
||||
results,
|
||||
wordCount: words.length,
|
||||
highlighted: highlighted.join(' ').replace(/&n/g, '\n'),
|
||||
}
|
||||
}
|
||||
|
||||
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: geniusKey,
|
||||
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
|
||||
|
||||
result.match = match
|
||||
|
||||
if (match > best) {
|
||||
best = match
|
||||
out = result
|
||||
}
|
||||
|
||||
if (match == target.length) break
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
export { filter, info }
|
||||
@@ -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 }
|
||||
@@ -0,0 +1,94 @@
|
||||
import { defaultVolume, verbose } from '../../env.js'
|
||||
|
||||
import { spawn } from 'child_process'
|
||||
import { updateStatus } from './calls.js'
|
||||
|
||||
class PlaybackError extends Error {
|
||||
constructor(message = '', ...args) {
|
||||
super(message, ...args)
|
||||
}
|
||||
}
|
||||
|
||||
var radio,
|
||||
busy = true,
|
||||
waiting = []
|
||||
|
||||
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) {
|
||||
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)
|
||||
|
||||
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 `vlc 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)
|
||||
}
|
||||
|
||||
function stream(track) {
|
||||
queueCommand('change', [track.url])
|
||||
player.play()
|
||||
queueCommand('volume', [defaultVolume])
|
||||
}
|
||||
|
||||
function local(track) {
|
||||
queueCommand('local', [`./cache/${track.tid}.mp4`])
|
||||
player.play()
|
||||
queueCommand('volume', [defaultVolume])
|
||||
updateStatus(track, 0, track.duration)
|
||||
}
|
||||
|
||||
export { stream, local }
|
||||
|
||||
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 }
|
||||
@@ -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,
|
||||
@@ -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 }
|
||||
@@ -0,0 +1,131 @@
|
||||
import spotifyToYt from 'spotify-to-yt'
|
||||
import { YouTube } from 'youtube-sr'
|
||||
import {
|
||||
createWriteStream,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
renameSync,
|
||||
statSync,
|
||||
} from 'fs'
|
||||
import ytdl from 'ytdl-core'
|
||||
|
||||
import { logAction, logError } from './log.js'
|
||||
|
||||
import Track from '../classes/Track.js'
|
||||
import { getTrack } from './calls.js'
|
||||
|
||||
const cache = './cache'
|
||||
|
||||
function convert(tids) {
|
||||
logAction(`Running converter`, tids.length)
|
||||
|
||||
return Promise.all(
|
||||
tids.map(async (tid) => {
|
||||
let { title, artists } = await getTrack(tid)
|
||||
|
||||
return await YouTube.search(
|
||||
`${title} ${artists.join(' ')} official audio`,
|
||||
{ limit: 10, type: 'video' }
|
||||
).then((videos) => {
|
||||
if (videos.length < 1) {
|
||||
logError('No videos found, retrying', tid)
|
||||
return YouTube.search(`${title} ${artists.join(' ')}`, {
|
||||
limit: 10,
|
||||
type: 'video',
|
||||
}).then((videos) => {
|
||||
if (videos.length < 1) {
|
||||
logError(`Conversion failed twice, I give up`, tid)
|
||||
} else return videos
|
||||
})
|
||||
} else return videos
|
||||
})
|
||||
})
|
||||
).then((ytd) => tids.map((tid, i) => new Track(tid, ytd[i])))
|
||||
|
||||
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 (!existsSync(cache)) {
|
||||
mkdirSync(cache)
|
||||
}
|
||||
|
||||
let stream = ytdl(url, {
|
||||
filter: (format) => {
|
||||
if (format.hasVideo) return false
|
||||
if (format.container == 'mp4') return false
|
||||
return true
|
||||
},
|
||||
}),
|
||||
file = createWriteStream(temp)
|
||||
|
||||
let written = 0
|
||||
|
||||
stream.on('data', (data) => {
|
||||
file.write(data, () => {
|
||||
written += data.length
|
||||
progress(data.length, written)
|
||||
})
|
||||
})
|
||||
|
||||
stream.on('end', () => {
|
||||
file.close(() => {
|
||||
renameSync(temp, final)
|
||||
end(final, written)
|
||||
resolve(final)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function check(path) {
|
||||
if (existsSync(path)) {
|
||||
let { size, atime } = statSync(path),
|
||||
daysAgo = (new Date().getTime() - atime.getTime()) / 1024 / 60 / 60 / 24
|
||||
|
||||
return { size, daysAgo }
|
||||
} else {
|
||||
return { size: null, daysAgo: null }
|
||||
}
|
||||
}
|
||||
|
||||
async function download(track) {
|
||||
const target = `${cache}/${track.tid}.mp4`
|
||||
|
||||
if (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, check }
|
||||
@@ -0,0 +1,37 @@
|
||||
import { limit } from '../env.js'
|
||||
|
||||
import { getTop } from './modules/calls.js'
|
||||
import { logSchedule, logTrack } from './modules/log.js'
|
||||
import { parse, scheduler } from './modules/parse.js'
|
||||
import { check, convert } from './modules/youtube.js'
|
||||
|
||||
export default async function schedule({
|
||||
checkCache = false,
|
||||
rolling = false,
|
||||
}) {
|
||||
const { schedule, tracks, ends } = await getTop(rolling ? 'rolling' : 'once') // tids
|
||||
.then((tids) => tids.slice(0, limit))
|
||||
.then(convert) // Tracks
|
||||
.then(parse) // chart
|
||||
.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]
|
||||
|
||||
if (checkCache) var { size } = check(`cache/${track.tid}.mp4`)
|
||||
|
||||
logSchedule(starts)
|
||||
logTrack(track, {
|
||||
color: checkCache ? (size ? undefined : 'red') : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
logSchedule(end, `#${przerwa} End`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
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 { convert } from './modules/youtube.js'
|
||||
import { parse, cache, scheduler } from './modules/parse.js'
|
||||
import { logAction, logSchedule, logTrack, logValue } from './modules/log.js'
|
||||
import { local } from './modules/playback.js'
|
||||
|
||||
export default async function standalone({ tids, rolling } = {}) {
|
||||
logValue('Volume', defaultVolume)
|
||||
logValue('Offset', offset)
|
||||
logValue('Verbose', verbose)
|
||||
logValue('Limit', process.env.LIMIT)
|
||||
console.log(rolling)
|
||||
const _tids = (tids ?? (await getTop(rolling ? 'rolling' : 'once'))).slice(
|
||||
0,
|
||||
limit
|
||||
) // tids
|
||||
|
||||
const { schedule, tracks, ends } = await convert(_tids) // 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)
|
||||
updateNext(_tracks[n + 1]?.tid ?? null)
|
||||
}, starts.to() * 1e3)
|
||||
}
|
||||
|
||||
// schedule END
|
||||
logSchedule(end, `#${przerwa} End`)
|
||||
|
||||
if (end.to() >= 0)
|
||||
setTimeout(() => {
|
||||
logAction(`» End of #${przerwa} «`)
|
||||
player.fadeOut(6)
|
||||
updateStatus(null, null, null, true)
|
||||
}, end.to() * 1e3)
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
logAction('≡≡≡ End of the day ≡≡≡')
|
||||
process.exit(0)
|
||||
}, (ends.at(-1).to() + 10) * 1e3)
|
||||
|
||||
logAction('Starting player')
|
||||
playback()
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import { getTop, updateNext, updateStatus } from './modules/calls.js'
|
||||
import { logAction } from './modules/log.js'
|
||||
import { cache } from './modules/parse.js'
|
||||
import playback, { local, player, queueCommand } from './modules/playback.js'
|
||||
import { convert } from './modules/youtube.js'
|
||||
|
||||
const delay = (n) => new Promise((r) => setTimeout(r, n))
|
||||
|
||||
export default async function test() {
|
||||
const tracks = await getTop() // tids
|
||||
.then((tids) => tids.slice(0, 3))
|
||||
.then(convert) // Tracks
|
||||
.then(cache)
|
||||
|
||||
playback()
|
||||
|
||||
for (let n in tracks) {
|
||||
logAction(`Playing track ${n + 1}/${tracks.length}`)
|
||||
local(tracks[n])
|
||||
player.play()
|
||||
updateNext(tracks[n + 1])
|
||||
await delay(10e3)
|
||||
}
|
||||
|
||||
logAction(`Fading out`)
|
||||
player.fadeOut(6)
|
||||
updateStatus(null)
|
||||
|
||||
await delay(7e3)
|
||||
queueCommand('exit')
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export default function web() {
|
||||
console.log('to be implemented')
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
import chalk from 'chalk'
|
||||
import yesno from 'yesno'
|
||||
|
||||
import { getTop, getTrack } from './modules/calls.js'
|
||||
import { logAction, logTrack, logValue } from './modules/log.js'
|
||||
import { filter, info } from './modules/lyrics.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({ susOnly, 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 (susOnly) return
|
||||
}
|
||||
|
||||
logTrack(track, options)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { YouTube } from 'youtube-sr'
|
||||
|
||||
let track = {
|
||||
_id: {
|
||||
$oid: '615c77f0c3a15512f3215f5c',
|
||||
},
|
||||
album: {
|
||||
art: [
|
||||
{
|
||||
height: 640,
|
||||
url: 'https://i.scdn.co/image/ab67616d0000b2735755e164993798e0c9ef7d7a',
|
||||
width: 640,
|
||||
},
|
||||
{
|
||||
height: 300,
|
||||
url: 'https://i.scdn.co/image/ab67616d00001e025755e164993798e0c9ef7d7a',
|
||||
width: 300,
|
||||
},
|
||||
{
|
||||
height: 64,
|
||||
url: 'https://i.scdn.co/image/ab67616d000048515755e164993798e0c9ef7d7a',
|
||||
width: 64,
|
||||
},
|
||||
],
|
||||
name: 'Whenever You Need Somebody',
|
||||
year: 1987,
|
||||
},
|
||||
artists: ['Rick Astley'],
|
||||
id: '4cOdK2wGLETKBW3PvgPWqT',
|
||||
title: 'Never Gonna Give You Up',
|
||||
duration: 213573,
|
||||
explicit: false,
|
||||
banned: false,
|
||||
createdAt: {
|
||||
$date: '2021-10-05T16:06:08.537Z',
|
||||
},
|
||||
updatedAt: {
|
||||
$date: '2021-10-29T18:24:06.903Z',
|
||||
},
|
||||
__v: 0,
|
||||
}
|
||||
|
||||
function max(arr) {
|
||||
return arr.reduce(
|
||||
(a, b, i) => (a[0] < b ? [b, i] : a),
|
||||
[Number.MIN_VALUE, -1]
|
||||
)
|
||||
}
|
||||
|
||||
var results = await YouTube.search(
|
||||
`${track.title} ${track.artists.join(' ')} official audio`,
|
||||
{ limit: 10, type: 'video' }
|
||||
)
|
||||
|
||||
console.log(results)
|
||||
|
||||
// let durations = results.map((video, i) => {
|
||||
// if (video.duration < track.duration) {
|
||||
// return video.duration / track.duration
|
||||
// } else {
|
||||
// return track.duration / video.duration
|
||||
// }
|
||||
// })
|
||||
|
||||
// console.log(durations)
|
||||
|
||||
// let keywords = results.map((video, i) => {
|
||||
// // console.log(i, video.title)
|
||||
// let total = 0
|
||||
// const words = [['audio', 1]]
|
||||
|
||||
// for (let [word, weight] of words)
|
||||
// if (video.title.toLowerCase().includes(word)) total += weight
|
||||
|
||||
// return total
|
||||
// })
|
||||
|
||||
// console.log(keywords)
|
||||
|
||||
// var maxViews = max(results.map(({ views }) => views))[0]
|
||||
|
||||
// let views = results.map((video, i) => {
|
||||
// // console.log(i, video.views, maxViews)
|
||||
// return 1 - Math.abs(maxViews - video.views) / (maxViews / 2)
|
||||
// })
|
||||
|
||||
// console.log(views)
|
||||
|
||||
// let sum = results.map((video, i) => durations[i] + keywords[i] + views[i])
|
||||
|
||||
// let [final, index] = max(sum)
|
||||
|
||||
// console.log(final, index, results[7])
|
||||
Reference in new issue
Block a user