stream-tools/music/public/music.js
ari melody 8a1fabf91a
fully-functioning music status!
- accessible via /music
- only detects strawberry for now
2026-06-13 03:10:06 +01:00

48 lines
1.7 KiB
JavaScript

const musicEl = document.getElementById("music");
const artworkEl = document.querySelector(".artwork");
const titleEl = document.querySelector(".title");
const artistEl = document.querySelector(".artist");
async function sync() {
const eventSource = new EventSource("/music/sse");
eventSource.addEventListener("open", () => {
console.log("Connected.");
eventSource.addEventListener("music", event => {
const nextTrack = JSON.parse(event.data)
console.log(`Now playing: ${nextTrack.artist} - ${nextTrack.title}`)
musicEl.classList.add("switching");
setTimeout(() => {
musicEl.classList.remove("switching");
titleEl.innerText = nextTrack.title;
artistEl.innerText = nextTrack.artist;
artworkEl.src = "/music/artwork?r=" + Math.round(Math.random() * 1_000_000);
}, 500);
});
eventSource.addEventListener("music-state", event => {
const data = JSON.parse(event.data)
console.log(data.playing ? "Music playing." : "Music paused.");
if (data.playing)
musicEl.classList.remove("paused");
else
musicEl.classList.add("paused");
});
const errListener = eventSource.addEventListener("error", () => {
eventSource.removeEventListener("error", errListener);
eventSource.close();
console.error("Connection lost, or an error has occurred.");
console.log("Attempting to reconnect...");
// TODO: stop reconnecting after 10 failed attempts
setTimeout(() => {
sync();
}, 1000);
});
});
}
sync();