feat: better states broadcast

This commit is contained in:
Mateusz Pstrucha committed 2021-09-29 00:42:26 +02:00
1 parent 899aa3abc2
commit ebef81eda3
2 files changed
+82 -7

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
+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,
},
])