1
Fork 0
bauke-xyz/source/js/listenbrainz.js

100 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-01-09 15:09:00 +00:00
/* global document window */
window.addEventListener("DOMContentLoaded", async () => {
const loop = async () => {
const listen = await getCurrentListen();
if (listen === undefined) {
return;
}
let image;
try {
image = await getCoverArt(listen);
} catch (error) {
console.warn(error);
}
insertHtml(listen, image);
};
2021-11-27 13:50:35 +00:00
await loop();
setInterval(loop, 5 * 60 * 1000);
2021-11-27 13:50:35 +00:00
});
async function getCoverArt(listen) {
const releaseMbid = listen.track_metadata.additional_info?.release_mbid;
if (releaseMbid === undefined) {
return;
}
2023-01-09 15:09:00 +00:00
const result = await window.fetch(
`https://coverartarchive.org/release/${releaseMbid}`,
{
headers: {
Accept: "application/json",
},
},
2023-01-09 15:09:00 +00:00
);
if (!result.ok) {
return;
}
const data = await result.json();
if (data.images[0]?.thumbnails === undefined) {
return;
}
const thumbnails = data.images[0].thumbnails;
2023-01-09 15:09:00 +00:00
return (
thumbnails.small ?? thumbnails["250"] ?? thumbnails["500"] ?? undefined
);
}
2021-11-27 13:50:35 +00:00
async function getCurrentListen() {
2023-01-09 15:09:00 +00:00
const result = await window.fetch(
"https://api.listenbrainz.org/1/user/BaukeXYZ/playing-now",
);
if (!result.ok) {
console.warn(result.status);
2022-03-28 13:18:16 +00:00
return;
}
const data = await result.json();
if (data.payload.listens.length === 0) {
2022-03-28 13:18:16 +00:00
return;
}
2021-11-27 13:50:35 +00:00
return data.payload.listens[0];
}
function insertHtml(listen, image) {
2022-03-28 13:18:16 +00:00
if (listen === undefined) {
2021-12-03 23:51:55 +00:00
return;
}
2023-01-09 15:09:00 +00:00
const existing = document.querySelector(".listenbrainz") ?? undefined;
2022-03-28 13:18:16 +00:00
if (existing !== undefined) {
2021-11-27 13:50:35 +00:00
existing.remove();
}
const text = `${listen.track_metadata.artist_name} - ${listen.track_metadata.track_name}`;
2023-01-09 15:09:00 +00:00
const alt = image === undefined ? "ListenBrainz Logo" : `${text} Cover Art`;
2023-01-09 15:09:00 +00:00
image = image ?? "https://listenbrainz.org/static/img/logo_big.svg";
image = image.startsWith("http://") ? "https" + image.slice(4) : image;
2022-03-28 16:18:06 +00:00
const listenHtml = `
<p class="listenbrainz">
<img alt="${alt}" title="${alt}" src="${image}">
<span class="byline">Currently listening to</span>
<a href="https://listenbrainz.org/user/BaukeXYZ/" target="_blank">
${text}
</a>
</p>`;
2023-01-09 15:09:00 +00:00
document
.querySelector(".page-header")
.insertAdjacentHTML("beforeend", listenHtml);
2021-11-27 13:50:35 +00:00
}