Player endpoints #11

Merged
Maathias merged 5 commits from player-endpoints into master 2021-09-29 00:43:46 +02:00
8 changed files with 219 additions and 32 deletions

No files matched your search

+78
View File
@@ -15,6 +15,7 @@ import {
import { byId, byQuery } from './spotify.js'
import Track from './Track.js'
import { broadcast as wsBroadcast } from './socket.js'
import { DbError } from './errors.js'
@@ -29,6 +30,29 @@ function getTrackRank(tid) {
else return rank + 1
}
function broadcast(cats) {
wsBroadcast(cats.map((cat) => ({ cat, ...current[cat] })))
}
const current = {
next: { tid: '6BfbSHE9ytCTF910g3wNdj' },
status: {
tid: '3OcyTN8Nz3bdne5aq9mMR5',
progress: 0,
duration: 29598,
paused: false,
timestamp: new Date(),
},
previous: {
combo: [
['0VdSlJ7owUK1MuS8Kp7LdE', '2021-09-09T21:41:44.528Z'],
['5svu5mLA4U2kdxPj1tLJ2I', '2021-09-09T21:41:44.528Z'],
],
},
}
const maxPrevious = 20
var topList = [],
lastTop = -1
@@ -168,6 +192,60 @@ const db = {
})
},
},
current: {
currentTimer: null,
get status() {
return current.status
},
set status(chunk) {
if (current.status.tid != chunk?.tid) {
// add new [tid, date]
current.previous.combo.unshift([
current.status.tid,
current.status.timestamp,
])
// pop on overfill
if (current.previous.combo.length > maxPrevious)
current.previous.combo.pop()
}
current.status = { ...current.status, ...chunk, timestamp: new Date() }
clearInterval(this.currentTimer)
let timer = (this.currentTimer = setInterval(() => {
if (current.status.progress + 1e3 > current.status.duration) {
current.status.progress = current.status.duration
return clearInterval(timer)
}
if (!current.status.paused) current.status.progress += 1e3
}, 1e3))
},
get next() {
return current.next
},
set next(chunk) {
current.next = chunk
},
get previous() {
return current.previous
},
update(data) {
if (!Array.isArray(data)) data = [data]
for (let { cat, content } of data) {
this[cat] = content
}
broadcast(data.map((chunk) => chunk.cat))
},
},
}
export default db
+21 -17
View File
@@ -10,6 +10,7 @@ import track from './routes/track.js'
import search from './routes/search.js'
import vote from './routes/vote.js'
import login from './routes/login.js'
import player from './routes/player.js'
dotenv.config()
@@ -25,6 +26,7 @@ app.use('/track', track)
app.use('/search', search)
app.use('/vote', vote)
app.use('/login', login)
app.use('/player', player)
www.listen(process.env.portHttp)
@@ -42,20 +44,22 @@ www.on('listening', function () {
var i = 0
setInterval(async () => {
broadcast([
{
cat: 'status',
trackid: db.top.list[i],
progress: 20e3 + new Date().getMilliseconds(),
paused: false,
},
{
cat: 'top',
trackids: await db.top.get(),
timestamp: db.top.lastCount,
},
])
i++
if (i >= db.top.list.length) i = 0
}, 10e3)
// setInterval(async () => {
// db.current.update([
// {
// cat: 'status',
// content: {
// tid: db.top.list[i],
// },
// },
// {
// cat: 'top',
// content: {
// tids: await db.top.get(),
// timestamp: db.top.lastCount,
// },
// },
// ])
// i++
// if (i >= db.top.list.length) i = 0
// }, 10e3)
+1 -1
View File
@@ -7,7 +7,7 @@ const track = new mongoose.Schema(
artists: [String],
album: {
name: String,
art: String,
art: Array,
year: Number,
},
duration: Number, // milliseconds
+105
View File
@@ -0,0 +1,105 @@
import dotenv from 'dotenv'
import express from 'express'
import spotifyToYt from 'spotify-to-yt'
import db from '../db.js'
import Track from '../Track.js'
dotenv.config()
const router = express.Router()
function update(data) {
if (!Array.isArray(data)) data = [data]
db.current.update(data)
}
const playerSecret = 'Bearer ' + process.env.playerSecret
// set current track
router.put(
'/set/status',
(
{
body: { tid, progress = null, duration = null, paused = null },
headers: { authorization },
},
res
) => {
if (authorization === undefined)
return res.status(401).end('Authorization required')
if (authorization != playerSecret)
return res.status(403).end('Token invalid')
if (tid === undefined) return res.status(400).end('"tid" field required')
if (tid.length < Track.length) return res.status(400).end('Invalid tid')
if (progress !== null)
if (typeof progress !== 'number')
return res.status(400).end('progress value invalid')
if (duration !== null)
if (typeof duration !== 'number')
return res.status(400).end('duration value invalid')
if (paused !== null)
if (typeof paused !== 'boolean')
return res.status(400).end('paused value invalid')
update({
cat: 'status',
content: {
tid,
...(progress !== null && { progress }),
...(duration !== null && { duration }),
...(paused !== null && { paused }),
},
})
res.json('true')
}
)
// set next track
router.put(
'/set/next',
({ body: { tid }, headers: { authorization } }, res) => {
if (authorization === undefined)
return res.status(401).end('Authorization required')
if (authorization != playerSecret)
return res.status(403).end('Token invalid')
if (tid === undefined) return res.status(400).end('"tid" field required')
if (tid.length < Track.length) return res.status(400).end('Invalid tid')
update({
cat: 'next',
content: { tid },
})
res.json('true')
}
)
router.get('/get/top/', ({ headers: { authorization } }, res) => {
if (authorization === undefined)
return res.status(401).end('Authorization required')
if (authorization != playerSecret) return res.status(403).end('Token invalid')
db.top.get().then((top) => {
Promise.all(
top.map((tid) => spotifyToYt.trackGet(`spotify:track:${tid}`))
).then((yts) => {
top.map((tid, i) => (yts[i].tid = tid))
res.json(yts)
})
})
})
export default router
+1 -1
View File
@@ -7,7 +7,7 @@ const router = express.Router()
router.post('/batch/', ({ body: { tids } }, res) => {
if (tids === undefined) return res.status(400).end('Track ids array required')
if (tids.length < 1) return res.end([])
if (tids.length < 1) return res.send([])
Promise.all(tids.map((tid) => db.tracks.get(tid)))
.then((tracks) => res.send(tracks))
+3 -3
View File
@@ -24,7 +24,7 @@ router.post(
if (tids === undefined)
return res.status(400).end('List of Track ids required')
if (tids.length < 1) return res.end([])
if (tids.length < 1) return res.json([])
Promise.all([
Promise.all(tids.map((tid) => db.votes.getTrackStats(tid))),
@@ -112,7 +112,7 @@ router.patch(
db.votes
.putUserTrack(tid, id, value)
.then((ok) => {
res.end(ok.toString())
res.json(ok.toString())
console.info(`vote# ${id} ${value} ${tid}`)
})
.catch((err) => {
@@ -121,7 +121,7 @@ router.patch(
})
})
.catch((err) => {
res.end('false')
res.json('false')
console.error(err)
})
}
+4 -7
View File
@@ -27,23 +27,20 @@ wss.on('connection', async function connection(ws, req) {
send([
{
cat: 'previous',
trackids: ['0VdSlJ7owUK1MuS8Kp7LdE', '5svu5mLA4U2kdxPj1tLJ2I'],
timestamps: ['2021-09-09T21:41:44.528Z', '2021-09-09T21:41:44.528Z'],
...db.current.previous,
},
{
cat: 'next',
trackid: '6BfbSHE9ytCTF910g3wNdj',
...db.current.next,
},
{
cat: 'top',
trackids: await db.top.get(),
tids: await db.top.get(),
timestamp: db.top.lastCount,
},
{
cat: 'status',
trackid: '3OcyTN8Nz3bdne5aq9mMR5',
progress: 0,
paused: false,
...db.current.status,
},
])
+6 -3
View File
@@ -1,10 +1,13 @@
import dotenv from 'dotenv'
import SpotifyWebApi from 'spotify-web-api-node'
import Track from './Track.js'
dotenv.config()
const spotify = new SpotifyWebApi({
clientId: 'c9cd1ede71914999a75fbea35313c1a4',
clientSecret: '13858e98eb264cf78251072f2ea5e96d',
clientId: process.env.spotifyClientId,
clientSecret: process.env.spotifyClientSecret,
})
function grantToken() {
@@ -45,7 +48,7 @@ function byId(id) {
artists: body.artists.map((a) => a.name),
album: {
name: body.album.name,
art: body.album.images[0].url,
art: body.album.images,
year: body.album.release_date.slice(0, 4),
},
duration: body.duration_ms,